Safe SQL, Permissions and Evaluation

Two separate questions: can this query do harm, and does it answer correctly? Each needs its own evidence.

BeginnerIntermediateExpert · 13 min read · Last updated:

In short

Make safety the database's job: narrow roles, curated views, row and column rules, read-only sessions and hard limits. Add a policy check on the parsed query before it runs. Measure correctness by comparing results, preferably on more than one data state, and test refusals and attacks as seriously as ordinary questions.

What you will learn: the harms a SQL agent can cause, layered permissions, row-level security and its exceptions, query validation and planning checks, execution accuracy, benchmark limits and production monitoring.
Prerequisites: Text-to-SQL Agents and Schema Linking.

Versions used

The example runs in November 2026 with Python 3.13 and only the standard library, using the SQLite engine included with Python. Tables and values are invented. Database features differ by product and version, so confirm behavior on your own system. This is defensive guidance.

Beginner What can go wrong

Five kinds of harm

HarmHow it happensMain defense
Changing dataA write or schema statement is generated or injectedNo write privileges
Seeing too muchBroad account, unmasked columns, other tenants' rowsUser identity and row and column rules
Using too muchCartesian joins, full scans, retry stormsTimeouts, quotas and cost limits
Inferring secretsNarrow aggregates reveal an individualMinimum group sizes and query review
Misleading peopleValid query, wrong meaningDefinitions, tests and visible assumptions

The first four are security and operations problems that controls can largely prevent. The fifth is a quality problem that only measurement and good definitions reduce. A system can be perfectly safe and badly wrong, or accurate on average and dangerous. Track both.

Assume the query may be hostile

Generated SQL should be treated like input from an unknown program. The model may misunderstand, a user may ask for something they should not have, and text retrieved from a table or document may carry instructions. Design so that the worst possible query, run under the agent's identity, causes limited and recoverable damage. This framing, used across Agent Threat Model and OWASP Agentic Risks, removes the need to predict every clever phrasing.

It also shows why keyword blocklists are weak. Rejecting the word DELETE does nothing about a function with side effects, a statement hidden in a comment trick, or a perfectly ordinary read of a table that should be private. It can also block a legitimate query about a column called "deleted_at".

Layers of control

Identifywho asks
Restrictgrants
Inspectparsed SQL
Limittime, rows
Recordaudit
  • Identify: pass the person's identity to the database, or map it to a role with no more access than they have.
  • Restrict: grant read access to specific views and columns only.
  • Inspect: parse the statement and check it against policy before execution.
  • Limit: cap duration, rows returned, bytes scanned, concurrency and attempts.
  • Record: log who asked, what ran, what was refused and how much it cost.
Intermediate Permissions, validation and example

Row and column permissions

Row-level security attaches a rule to a table so that each user sees only permitted rows, whatever query they send. PostgreSQL documents this as row security policies, and many warehouses offer similar row access policies and column masks. Read the exceptions closely.

  • In PostgreSQL, superusers and roles with the bypass attribute skip row security, and table owners normally do too unless it is forced on the table.
  • A view or function may run with its creator's rights instead of the caller's, depending on how it is defined.
  • Connection pools that share one database user need a reliable way to set the end user's context on every request and clear it afterward.
  • Extracts, caches, search indexes and result files do not inherit the table's rules automatically.
  • Error messages, row counts and timing can hint at data a user cannot read.

Test with real roles. For each role, assert which rows and columns come back, including through views, joins and aggregate queries. Include a user with no entitlement, who should receive nothing.

Columns, masking and small groups

Decide per column whether an agent needs the real value. Often it needs only to group or count. Offer masked, bucketed or hashed versions in the views the agent can use, remembering that a hash of a guessable value such as an email address can be reversed by guessing and is still personal data in many legal regimes. For aggregates over people, suppress groups below a minimum size and watch for sequences of overlapping queries that isolate one person by subtraction. A threshold alone does not stop that; limit the dimensions available or use a formally protected method where the stakes require it. See PII Redaction and Data Leakage Prevention.

Validate and plan before running

CheckQuestion
ParseIs it exactly one statement in the expected dialect?
Statement typeIs it a read, including every nested part?
ObjectsAre all tables, views and columns on the allow-list?
FunctionsIs every function on an approved list?
ShapeJoins without conditions, missing partition filters, unbounded recursion?
Plan or dry runAre estimated rows, bytes or cost within limits?
IntentDoes it use the metric, filters and period that were agreed?

Use the database's own parser or authorization hooks where possible, because a separate parser can disagree with the engine about unusual syntax. Plan estimates are approximations, so keep the runtime limits even when the estimate looks small.

Limits that hold under pressure

  • A statement timeout set on the database side.
  • A maximum number of rows and bytes returned to the agent.
  • Budgets per question, per user and per day, covering retries.
  • A separate compute pool or replica for agent queries.
  • Cancellation when the user leaves or the run is stopped.
  • A switch that disables free-form queries while keeping certified metrics.

Say clearly when a result was cut off. A truncated list presented as complete is a correctness failure created by a safety control.

Gate the query, then score the answer

The program installs a SQLite authorizer that allows reads of four columns in one table and two aggregate functions. It then scores six candidate queries against a reference query on two versions of the data. The second version contains a voided order and a repeated amount.

"""Score generated SQL by results on two databases, behind a safety gate."""
import sqlite3
from collections import Counter

ALLOWED = {"orders": {"id", "region", "amount", "status"}}

BASE = [(1, "north", 100, "paid"), (2, "north", 250, "paid"),
        (3, "south", 400, "paid")]
EXTRA = BASE + [(4, "south", 900, "void"), (5, "north", 100, "paid")]


def make(rows):
    db = sqlite3.connect(":memory:")
    db.execute("CREATE TABLE orders (id INTEGER, region TEXT,"
               " amount INTEGER, status TEXT)")
    db.execute("CREATE TABLE payroll (name TEXT, pay INTEGER)")
    db.executemany("INSERT INTO orders VALUES (?,?,?,?)", rows)

    def guard(action, arg1, arg2, *_):
        if action == sqlite3.SQLITE_SELECT:
            return sqlite3.SQLITE_OK
        if action == sqlite3.SQLITE_READ and arg2 in ALLOWED.get(arg1, ()):
            return sqlite3.SQLITE_OK
        if action == sqlite3.SQLITE_READ and arg1 in ALLOWED and arg2 == "":
            return sqlite3.SQLITE_OK
        if action == sqlite3.SQLITE_FUNCTION and arg2 in ("sum", "count"):
            return sqlite3.SQLITE_OK
        return sqlite3.SQLITE_DENY

    db.set_authorizer(guard)
    return db


def run(db, sql):
    return Counter(db.execute(sql).fetchmany(1000))


GOLD = ("SELECT region, SUM(amount) FROM orders"
        " WHERE status = 'paid' GROUP BY region")
CANDIDATES = {
    "same text": GOLD,
    "rewritten": "SELECT region, SUM(amount) AS total FROM orders "
                 "WHERE status IN ('paid') GROUP BY 1 ORDER BY 2",
    "no filter": "SELECT region, SUM(amount) FROM orders GROUP BY region",
    "distinct bug": "SELECT region, SUM(DISTINCT amount) FROM orders "
                    "WHERE status = 'paid' GROUP BY region",
    "reads payroll": "SELECT name, pay FROM payroll",
    "writes": "DELETE FROM orders",
}

first, second = make(BASE), make(EXTRA)
print(f"{'candidate':<15}{'text':<7}{'db 1':<7}{'db 2':<7}verdict")
for name, sql in CANDIDATES.items():
    text = "yes" if sql == GOLD else "no"
    try:
        one = run(first, sql) == run(first, GOLD)
        two = run(second, sql) == run(second, GOLD)
    except sqlite3.DatabaseError as error:
        print(f"{name:<15}{text:<7}{'-':<7}{'-':<7}blocked: {error}")
        continue
    verdict = "pass" if one and two else "fail"
    if one and not two:
        verdict = "fail (first database was fooled)"
    mark = lambda ok: "match" if ok else "differ"
    print(f"{name:<15}{text:<7}{mark(one):<7}{mark(two):<7}{verdict}")

Output:

candidate      text   db 1   db 2   verdict
same text      yes    match  match  pass
rewritten      no     match  match  pass
no filter      no     match  differ fail (first database was fooled)
distinct bug   no     match  differ fail (first database was fooled)
reads payroll  no     -      -      blocked: access to payroll.name is prohibited
writes         no     -      -      blocked: not authorized

Comparing text would have failed the rewritten query, which is correct. Comparing results on the first database alone would have passed two broken queries: one that forgets the paid filter and one that adds only distinct amounts. The first data set simply contained nothing that exposed them. The payroll read and the delete never run at all, regardless of how they were produced. This authorizer is specific to SQLite and to this tiny example; on a server database, grants and policies do this work.

Measures of correctness

MeasureWhat it comparesBlind spot
Exact matchQuery text or structureRejects equivalent queries
Execution accuracyResult setsCoincidental agreement on thin data
Multi-state executionResults across several data setsOnly as strong as the data you design
Component checksTables, filters, grouping, periodSeveral valid ways to write a query
Human reviewMeaning and presentationSlow, and reviewers can disagree
BehaviorAsked, refused or answered appropriatelyNeeds agreed expectations

Result comparison needs rules. Decide whether row order matters, how to compare decimals, whether extra columns are acceptable and how nulls are treated. Write these down before scoring, so that nobody adjusts them after seeing which system wins.

Design test data that can catch errors

Good test data is built to separate right queries from tempting wrong ones. Add rows that:

  • Sit exactly on date boundaries, and in neighboring time zones.
  • Have nulls in join keys, filters and measures.
  • Share equal values, so that removing duplicates changes totals.
  • Include every status, including canceled, void and test records.
  • Create one-to-many joins that duplicate parents.
  • Leave a group with no rows, to test how absence is reported.

When a wrong query passes, add the row that would have caught it. This habit matters more than the size of the data.

Expert Benchmarks, safety testing and operations

Read benchmark scores with care

Public leaderboards help compare methods, but their reference answers can be wrong. A study presented at CIDR 2026, Text-to-SQL Benchmarks are Broken, reported annotation error rates of 52.8% in the audited BIRD subset and 66.1% in the audited Spider 2.0-Snow examples, and found that method performance shifted after corrections. An extended version re-evaluated more BIRD systems and saw rankings move by several places in both directions. Those figures apply to the audited samples, not to every item. The lesson for your own work is direct:

  • Have two people agree on reference queries for important cases.
  • Inspect disagreements between your system and the reference; sometimes the reference is wrong.
  • Treat small score differences as noise until repeated on your data.
  • Note which benchmark version and corrections a published score used.

Your evaluation set

Draw questions from real requests, remove sensitive details and label each with intent, difficulty, domain and expected behavior. Keep a held-out portion that prompt authors do not see. Run several trials, since generation can vary, and report the share of cases that pass every time as well as the average. Break results down by domain, because an overall figure can hide one area where the agent should not yet be used. Golden Datasets, Synthetic Data and Simulation and Task, Tool and Planning Metrics go further.

CategoryExpected behavior
Clear questionCorrect result and stated assumptions
Ambiguous questionA specific clarifying question
UnanswerableSays what is missing
Not permittedRefuses without revealing restricted detail
ExpensiveAsks to narrow, or stops at the limit
AdversarialNo policy violation; event is recorded

Test execution safety separately

Safety tests should not depend on the model behaving well. Feed forbidden statements straight to the execution gateway and confirm that each is refused: writes, schema changes, multiple statements, access to excluded objects, risky functions, runaway queries and attempts to change session settings. Then run end-to-end tests with hostile questions and with planted instructions in data. A pass means that the control held, even if the model tried something it should not have. Keep these tests in the release pipeline, because a new grant or view can silently open access. Red Teaming and Incident Response describes how to organize this work.

Release rules

  • Any safety test failure blocks release.
  • Accuracy must meet a threshold per domain, agreed with its owner.
  • Confident wrong answers on high-impact cases block release until understood.
  • Cost and latency changes are reviewed, not just accuracy.
  • Schema or metric changes trigger the affected subset automatically.

Monitor in production

Real use differs from the test set. Watch refusal and clarification rates, corrections, retries, queries stopped by limits, unusual access patterns and users who stop returning. Sample answers for analyst review, weighted toward high-impact domains. Compare agent totals with trusted reports for a few standing questions every day; a mismatch is an early warning that a definition, load or schema has changed. Protect the logs, which contain questions and queries that may reveal sensitive matters, as described in Safe Logging, Sampling and Retention.

When something goes wrong

  1. Disable free-form queries or the affected domain.
  2. Find every question that used the faulty definition, grant or version.
  3. Tell people who received wrong or excessive data, following your incident and privacy process.
  4. Fix the control closest to the data first.
  5. Add a test that fails without the fix.

Common mistakes

MistakeConsequenceInstead
Blocklisting keywordsBypasses and false blocksGrants, parsing and allow-lists
Testing row security as an ownerRules look fine but never appliedTest with the real runtime role
Scoring on one small data setWrong queries passSeveral states with trap rows
Trusting reference answers blindlyOptimizing toward errorsReview disagreements
Counting refusals as failures onlyAgent learns to guessScore appropriate abstention
Silent truncationPartial results read as completeShow limits that were hit

Checklist

  • The runtime identity cannot write or change schema.
  • Row and column rules are tested with each real role.
  • Only parsed, single, allow-listed read statements run.
  • Time, row, cost and retry limits are enforced outside the model.
  • Evaluation data includes rows designed to expose likely errors.
  • Reference answers have been reviewed.
  • Safety tests run directly against the gateway on every release.
  • A disable switch and an incident procedure exist.

Frequently asked questions

Is a read replica enough to make an agent safe?

It protects the primary from writes and load, but anything readable on the replica can still be exposed, so permissions are needed there too.

Can a second model check the SQL?

It may catch some mistakes of meaning and is worth measuring. It should not be the control that prevents forbidden access.

What accuracy is good enough?

It depends on the decision, the review that follows and the cost of an error. Agree thresholds per domain with the people accountable for the figures.

How large should the test set be?

Large enough to cover each domain and failure type with several cases. Grow it from real mistakes instead of aiming at a round number.

References

Where to go next