Data Engineering · 7 min read
Text-to-SQL in production: schema context, guardrails and evaluation
Models now write good SQL on clean demos, but production databases are bigger, messier and riskier. Here's how to give a text-to-SQL system the right schema context, lock down what it can execute, and evaluate it honestly.
“Ask your data a question in plain English” is one of the oldest LLM demos, and the demo works. Point a current model at a tidy ten-table database and it will write correct SQL most of the time.
Production is different. Warehouses have thousands of tables, cryptic column names, three versions of “revenue” and data that nobody fully documented. A wrong answer doesn’t throw an error — it returns a confident, plausible number that ends up in a slide.
This post covers the three things that decide whether text-to-SQL survives contact with real users: schema context, guardrails and evaluation. (For the wider picture of agents in data work, see our post on data engineering agents.)
Why the demo and production diverge
The Spider 2.0 benchmark was built to measure exactly this gap. It has 632 tasks over 213 real databases on systems including BigQuery, Snowflake, PostgreSQL and DuckDB. The databases average roughly 740–810 columns, some exceed 1,000, and tasks need dialect-specific functions, multi-step queries and sometimes reading a dbt project.
When it was released, the best agent setup (o1-preview with the authors’ Spider-Agent) solved 21.3% of tasks, against scores the paper cites of 91.2% on the original Spider and 73.0% on BIRD for GPT-4-based methods. Models have improved since, but the authors’ list of what makes the problem hard still reads like a production bug tracker:
- Schema linking: picking the right tables and columns from a huge schema, often without foreign keys.
- Dialect quirks: date, geography and nested-field functions that differ per warehouse.
- Query planning: CTEs, nested queries and set operations rather than one
SELECT. - Business context: knowledge that lives in docs and code, not in the schema.
Almost all of these are context problems, not SQL-writing problems.
Schema context: give the model less, but better
Dumping the whole schema into the prompt stops working once you have more than a few dozen tables. The pattern that works is retrieval plus curation.
1. Retrieve tables, don’t list them. Pinterest’s engineering team described indexing LLM-written summaries of their top-tier tables (built from the schema plus recent queries that used each table), embedding the user’s question, retrieving candidate tables, and asking the LLM to narrow them down. The user then confirms or edits the table list before any SQL is written. They reported that table-retrieval hit rate rose from 40% to about 90% as they gave table documentation more weight in the embeddings, and first-shot acceptance of generated SQL rose from 20% to over 40%. That post is from 2024, but the lesson — documentation is the retrieval signal — has held up.
2. Describe what columns mean. A column called amt_net tells the model nothing about currency, refunds or tax. Short descriptions, allowed values for low-cardinality columns, and known join paths do more than a bigger model.
3. Add verified examples. Snowflake’s Cortex Analyst lets you store a Verified Query Repository: trusted natural-language questions paired with checked SQL, optionally recording who verified each one. When a new question is similar to a verified one, Cortex Analyst uses that SQL to shape its answer. The same idea works anywhere — keep a small library of trusted question/SQL pairs and retrieve the closest few as examples.
4. Consider a semantic layer for the numbers that matter. dbt Labs’ April 2026 benchmark compared raw text-to-SQL with a semantic layer, where the model picks metrics and dimensions and dbt’s MetricFlow generates the SQL deterministically. On an insurance dataset, with light modelling added, Claude Sonnet 4.6 scored 90.0% with text-to-SQL vs 98.2% via the semantic layer; GPT-5.3 Codex scored 84.1% vs 100%. The more important finding was about how each fails: text-to-SQL can return plausible but wrong numbers, while the semantic layer returns an error when a question falls outside what has been modelled.
The trade-off is coverage. Questions that needed more joins than MetricFlow supports scored 0% on the semantic layer in the same test. dbt’s recommendation is a fallback order: try the semantic layer, then see whether a small modelling change would cover the question, and only then fall back to text-to-SQL with as much schema context as you can give.
| Semantic layer | Text-to-SQL | |
|---|---|---|
| Best for | KPIs, recurring reports, anything audited | Ad hoc exploration, long-tail questions |
| Failure mode | Refuses out-of-scope questions | Can return a wrong number silently |
| Up-front cost | Modelling metrics and joins | Documentation and examples |
Guardrails: assume the model will be tricked
A text-to-SQL system is a program that turns untrusted text into code and runs it against your data. Treat it that way.
Research by Pedro et al. on prompt-to-SQL (P2SQL) injection tested LangChain and LlamaIndex apps across seven LLMs. With default prompts, chatbots generated whatever SQL users asked for, including dropping tables and dumping data. Adding “only run SELECT” style instructions to the prompt didn’t fix it: the authors found prompt restrictions “insufficient to fully prevent direct P2SQL attacks.” They also showed an indirect variant, where malicious instructions stored in a database record (a job description, say) are followed when the model later reads that row for another user.
Their proposed defences, plus the database-level controls they mention, give a sensible layered setup:
- Read-only credentials, enforced by the database. The connection the model uses should be physically unable to write. This is the one guardrail that doesn’t depend on the model behaving.
- Row- and column-level access per user. Run queries as (or on behalf of) the asking user, so the model can’t see data the user can’t. The paper’s approach rewrites queries to restrict them to authorised data; warehouse-native row-level security does the same job.
- Parse before you execute. Use a SQL parser to allow only
SELECT, block multiple statements, and reject tables outside an allow-list. - Cost and size limits. Add timeouts, row limits and, on cloud warehouses, a bytes-scanned cap, so one bad join can’t run up a bill.
- Treat query results as untrusted input before they go back into the model’s context.
A minimal pre-execution check might look like this:
import sqlglot
from sqlglot import exp
ALLOWED_TABLES = {"orders", "customers", "products"}
def check_sql(sql: str, dialect: str = "snowflake") -> str:
statements = sqlglot.parse(sql, read=dialect)
if len(statements) != 1:
raise ValueError("Exactly one statement allowed")
tree = statements[0]
if not isinstance(tree, exp.Select): # extend if you allow UNION etc.
raise ValueError("Only SELECT queries are allowed")
tables = {t.name.lower() for t in tree.find_all(exp.Table)}
if not tables <= ALLOWED_TABLES:
raise ValueError(f"Disallowed tables: {tables - ALLOWED_TABLES}")
if not tree.args.get("limit"):
tree = tree.limit(1000)
return tree.sql(dialect=dialect)
This is a second line of defence, not the first. The read-only credential is what actually protects you.
Evaluation: check your test set before you trust it
You need your own evaluation set: real questions from your users, each with SQL a domain expert has checked, scored by comparing result sets rather than SQL strings (two different queries can both be right).
Be careful how much you trust public leaderboards — and your own gold answers. In a July 2026 write-up of their research, Daniel Kang’s group reported annotation errors in 52.8% of BIRD Mini-Dev examples and 62.8% of Spider 2.0-Snow examples. After correcting a subset, agent rankings shifted by up to nine places; the previous top system fell from 1st to 7th. The most common error type was a mismatch between the “correct” query and the actual data, caused by weak understanding of the schema — the same mistake models make.
Practical consequences for your own eval set:
- Have a second person review gold SQL, and re-check it when the schema changes.
- Inspect failures by hand. A “wrong” answer is sometimes a wrong label.
- Track more than accuracy: correct refusals on unanswerable questions, table-retrieval hit rate, latency and cost per query.
- Run it on every change to prompts, models, documentation or the semantic model.
dbt’s benchmark also offers a useful warning on model choice: in their test, Claude Opus 4.6 did worse than the smaller Sonnet 4.6, and higher reasoning effort on GPT models roughly doubled latency without improving semantic-layer accuracy. Measure on your data rather than assuming bigger is better.
Trade-offs
- Coverage vs correctness. A semantic layer is reliable but narrow; free-form SQL answers more but can be wrong silently.
- Autonomy vs review. Letting users confirm tables or see the SQL adds friction but catches mistakes early.
- Context size vs focus. More schema helps recall but buries the relevant tables. Retrieval quality matters more than window size.
- Documentation cost. Most of the accuracy gains above came from metadata work, which someone has to own.
Where to start
- Pick one domain — say, orders and customers — not the whole warehouse.
- Write descriptions for its key tables and columns, and collect 20–50 verified question/SQL pairs.
- Lock down the connection: read-only, user-scoped, with timeouts and row limits, plus a parser check.
- Build an eval set from real questions, reviewed by two people, scored on result sets.
- Put core metrics behind a semantic layer if you have one, and use text-to-SQL for the long tail.
- Show users the SQL and tables used, so a wrong answer can be spotted before it becomes a decision.
Text-to-SQL is no longer limited by the model’s ability to write SQL. It’s limited by how well you describe your data, how tightly you control what runs, and how honestly you measure the results.