Skip to content
NewSecurity Audit for AI-Built Apps. Fixed scope, clear report
GeekTech
AI Security

Text-to-SQL Security: How to Let an LLM Query Your Data

Text-to-SQL security in practice: run LLM-generated SQL as a read-only role over scoped views, parse every query, pin the tenant and cap every result.

6 min read

GeekTech Engineering Team18 years building and securing software

To secure text-to-SQL, assume the model will eventually write whatever query an attacker wants, and make your code and the database refuse the dangerous ones. Run generated SQL as a dedicated read-only role that sees only purpose-built views. Parse every query and allow a single SELECT with approved functions, pin the tenant in code, and enforce timeouts and row limits. A system prompt saying "only write SELECT statements" helps the model behave, but it stops no one.

Why text-to-SQL is a security risk

OWASP lists this pattern under LLM10:2026 Improper Output Handling. In its third scenario, a user asks a chat feature for a query that deletes every table, and if nothing checks the generated SQL, the tables are gone.

Dropped tables are the loud failure. The others are harder to notice:

  • Reading other customers' rows, or columns such as password hashes, tokens and internal notes.
  • Expensive queries, such as a cross join over two large tables, that tie up the database.
  • Statements or functions that change session settings your other controls depend on.
  • Instructions hidden in stored data, such as a ticket body, that reach the model through query results.

Choose how much SQL the model writes

Free-form SQL is one option among several, and the riskiest.

ApproachWhat the model producesRiskGood fit
Fixed queries as toolsA tool name plus parameters, such as revenue_by_month(start, end)Low: you own the SQL, values are bound parametersCustomer-facing features with known questions
Structured query specJSON naming a metric, dimensions and filters from an approved list, compiled to SQL by your codeMedium: your compiler decides what is reachableSelf-serve reporting
Free-form SQLA complete SQL statementHigh: every control below is requiredInternal analysis of non-sensitive data

Start at the top row and move down only when users need questions you can't predict. With tools, your code holds the SQL and the model fills in values, as described in securing AI agents that use tools. The rest of this post assumes free-form SQL.

Run generated SQL as a read-only database role

The database role holds when the prompt and the parser fail. The OWASP SQL Injection Prevention Cheat Sheet recommends deciding what access an account needs from the ground up, giving read-only accounts only read access, and using views to limit which fields an account can see. A minimal PostgreSQL setup:

CREATE ROLE ai_reader LOGIN;  -- credentials come from your secret store
CREATE SCHEMA ai_views;
 
CREATE VIEW ai_views.orders WITH (security_barrier) AS
  SELECT id, created_at, status, total_amount
  FROM public.orders
  WHERE tenant_id = current_setting('app.tenant_id')::uuid;
 
GRANT USAGE ON SCHEMA ai_views TO ai_reader;
GRANT SELECT ON ALL TABLES IN SCHEMA ai_views TO ai_reader;
 
ALTER ROLE ai_reader SET statement_timeout = '5s';
ALTER ROLE ai_reader SET default_transaction_read_only = on;

PostgreSQL grants no table privileges to PUBLIC by default, so this role reads only what you grant. Two details matter.

Give the feature its own login. Don't connect as the application's main user and drop privileges with SET ROLE: the PostgreSQL SET ROLE documentation states that RESET ROLE can be executed by any user, so a generated query containing it gets the original privileges back.

Treat the timeout and read-only settings as defaults: a session can override both with SET. They catch what the parser misses. The grants are the boundary.

Expose views, not tables

Views leave out columns the feature doesn't need, such as password hashes, tokens and personal data, and they apply the tenant filter. They also give the model a few clear column names instead of a wide legacy table.

Check how views interact with row-level security (RLS). By default, a PostgreSQL view reads the underlying table with its owner's privileges and policies, and table owners normally bypass RLS. So a plain view can skip policies written for application users, like those in our post on Supabase row-level security mistakes. Either put the filter in the view and mark it security_barrier, as PostgreSQL recommends for views meant to provide row-level security, or set security_invoker = true so the caller's privileges and policies apply.

Parse and check every query before it runs

Use a real parser for your dialect, such as libpg_query, which is built from PostgreSQL's own parser. Regex and "starts with SELECT" checks miss comments, quoted identifiers and data-modifying WITH clauses: PostgreSQL accepts WITH d AS (DELETE ...) SELECT ... as one statement that deletes rows.

Check, in order:

  1. The input is exactly one statement. Also execute it through the extended query protocol (prepared statements), which rejects multiple statements, unlike the simple query protocol.
  2. It's a SELECT with no data-modifying WITH, no SELECT INTO (which creates a table) and no locking clause such as FOR UPDATE.
  3. Every relation it references is in the allowed schema, which excludes the system catalogs.
  4. Every function it calls is on an allowlist. PostgreSQL grants EXECUTE on functions to PUBLIC by default.
  5. A wrapper enforces the row cap: SELECT * FROM (<generated query>) AS q LIMIT 1000.

The function allowlist matters. set_config does the job of SET from inside a SELECT, and PostgreSQL accepts a value for any two-part setting name. The view above trusts app.tenant_id, so a query calling set_config('app.tenant_id', ...) can change what the view reads. Block pg_sleep too, and anything that reaches files or other servers.

Scope every query to the user's tenant

Take the tenant from the authenticated session, never from the conversation or the model's output. Per request:

  1. Open a read-only transaction on the ai_reader connection.
  2. Set the tenant for that transaction only, with a bound parameter: SELECT set_config('app.tenant_id', $1, true). Your code may call set_config. The model's query may not.
  3. Run the validated query as a prepared statement.
  4. Commit, so the setting ends with the transaction and can't leak to the next request on a pooled connection.

For more sensitive data, use a login role or schema per tenant. That adds roles and migrations to manage, but isolation then rests on grants instead of a setting.

Treat query results as untrusted input

Results flow to the model, the screen and your logs.

  • Cap the rows and characters passed back to the model, and keep the model that reads results away from tools that write data or send messages.
  • Render results as data with encoding for each context, as covered in our post on LLM output handling.
  • Log the question, generated SQL, user, tenant, row count and every rejection. A run of rejections from one account can mean someone is probing.

Common text-to-SQL security mistakes

  • Treating the system prompt as the control.
  • Connecting as the application's main database user, or switching down with SET ROLE.
  • Granting SELECT on whole tables, credential columns included.
  • Taking the tenant ID from the chat or from tool arguments.
  • No timeout or row limit, so one question can slow the primary database.

How to test a text-to-SQL feature

Run these in staging with two test tenants, and again when you add a view, a function or a model.

  1. Ask for writes directly. Request deletes, updates and new tables. The validator should refuse each, and so should the database when the same SQL is sent to it as ai_reader.
  2. Hide writes inside reads. Try a data-modifying WITH, SELECT INTO and a second statement after a semicolon.
  3. Reach for hidden data. Ask for columns outside the views, the system catalogs and the schema itself.
  4. Cross the tenant line. As tenant A, ask for tenant B's records, then try set_config and RESET ROLE.
  5. Exhaust resources. Send cross joins, recursive queries and pg_sleep. Confirm the timeout fires and the row cap holds.
  6. Inject through stored data. Save a record whose text tells the model to run a different query, then ask a question that returns it.

Where you can, send steps 1 to 5 straight to the validator and the database, so you test the controls rather than the model.

If you're shipping a feature like this, our LLM and AI agent security testing covers tool and function-call abuse, attempts to extract other users' data, and how model output is passed to other systems.

Frequently asked questions

Is a read-only database user enough for text-to-SQL?

No. It stops writes, but reads alone can expose other tenants' rows or sensitive columns, and a heavy query can still slow the database. Pair it with scoped views, a parser and limits.

How much of the schema should the model see?

Only the views it can query, with a short description of each column. Leave base tables and other schemas out of the prompt, and assume anything in the prompt can be shown to the user.

Can the model fix its own rejected queries?

Yes. Returning the validator's error and allowing one or two retries lets an honest question recover from a wrong column name. Return a generic reason rather than the full rule list, and count retries per user.

Insights

Related insights

More on AI Security →

Get AI security and automation insights, monthly

AI security, automation and governance, written by engineers. No spam, unsubscribe any time.

Book a free 30-min call