Text to SQL accuracy: why LLMs get warehouse SQL wrong
The five ways LLM-generated SQL returns a confident wrong number on a real warehouse (metrics, fan-out joins, dates, nulls, approximations) and the grounding techniques that fix each one.
Text-to-SQL accuracy is high on academic benchmarks and much lower on real warehouses, because the hard part is not SQL syntax but knowing what the business means. The evidence is consistent. The Spider 2.0 paper (ICLR 2025) reported that an o1-preview-based agent solved 91.2% of Spider 1.0 and 73.0% of BIRD, but only 21.3% of 632 enterprise-style workflow tasks. The latest revision of the BEAVER benchmark, built from private enterprise warehouses and their query logs, reports 10.8% for agentic frameworks on GPT-5.2, and 30.1% even with oracle hints. A 2023 study on an insurance schema found GPT-4 answered 16% of enterprise questions correctly from raw SQL tables, rising to 54% over a knowledge graph of the same data. The failures are rarely syntax errors. They are queries that run, return a plausible number, and are wrong. Below: five common patterns behind those wrong answers, each reproduced on ClickHouse 26.9, and the grounding techniques that fix them, in order of strength.
Why is text-to-SQL accuracy so much lower on real warehouses?
Academic benchmarks ask questions whose answer is fully determined by the schema. “How many singers are older than 30?” has one correct query. Business questions are different: “What was revenue last month?” depends on decisions that live in people’s heads, not in column names. Does revenue include cancelled orders? Is it net of refunds? Which time zone defines “last month”?
Three properties of real warehouses make this worse:
| Property | Benchmark database | Real warehouse |
|---|---|---|
| Schema size | A handful of tables | Hundreds or thousands of tables, many near-duplicates |
| Naming | Descriptive (singer.age) | Abbreviated, legacy, inconsistent (amt_net2, is_tst) |
| Business rules | None, or given as “evidence” | Implicit: filters, exclusions and grain known only to the team |
| Dialect | Usually SQLite | ClickHouse, Snowflake, BigQuery, each with its own semantics |
BIRD acknowledges the rules gap directly: its questions come with external knowledge evidence, hints such as which value of a column means an account owner, and the leaderboard has an “Oracle Knowledge” column flagging entries that use it. Your users will not supply it with every question.
The consequence matters more than the percentage. A syntax error is visible and gets fixed. A wrong WHERE clause produces a chart that looks fine and gets pasted into a board deck. dbt Labs put it plainly in their 2026 benchmark update: “With text-to-SQL, failure looks like a plausible but incorrect answer.”
The five ways LLM-generated SQL goes wrong
The examples below use three small tables. Every result shown was produced on ClickHouse 26.9.
CREATE TABLE customers (customer_id UInt64, name String, country LowCardinality(String))
ENGINE = MergeTree ORDER BY customer_id;
CREATE TABLE orders
(
order_id UInt64,
customer_id UInt64,
status LowCardinality(String), -- 'paid' | 'cancelled'
amount_eur Decimal(12, 2),
ordered_at DateTime('UTC')
)
ENGINE = MergeTree ORDER BY (ordered_at, order_id);
CREATE TABLE order_items (order_id UInt64, sku String, qty UInt32)
ENGINE = MergeTree ORDER BY order_id;
INSERT INTO customers VALUES (101,'Acme','DE'), (102,'Bolt','DE'), (103,'Cora','FR'), (104,'Dune','FR');
INSERT INTO orders VALUES
(1, 101, 'paid', 120.00, '2026-09-03 10:00:00'),
(2, 102, 'paid', 80.00, '2026-09-14 16:20:00'),
(3, 103, 'cancelled', 200.00, '2026-09-20 09:05:00'),
(4, 103, 'paid', 150.00, '2026-09-30 18:30:00');
INSERT INTO order_items VALUES (1,'A',1), (1,'B',2), (1,'C',1), (2,'A',1), (3,'B',1), (4,'A',1), (4,'C',3);
Paid revenue for September is 350 (120 + 80 + 150). Watch how many ways a model can miss it.
1. The ambiguous metric
Ask “what was revenue in September?” and a model with only the schema has to guess the filter. Most often it sums everything:
SELECT sum(amount_eur) FROM orders
WHERE ordered_at >= '2026-09-01' AND ordered_at < '2026-10-01';
-- 550: includes the cancelled order
The SQL is valid and the logic is reasonable. It is wrong only because nobody told the model that cancelled orders do not count. Real definitions carry more of these decisions: test accounts, refunds, currency, time zone. We walk through a revenue metric that returns three different numbers from the same six rows in what is a semantic layer. This is a common text-to-SQL failure, and no model improvement fixes it, because the missing information is not in the database.
2. The fan-out join
Ask “revenue and units sold for paid orders”. The model joins orders to their line items and sums both:
SELECT sum(o.amount_eur) AS revenue, sum(i.qty) AS units
FROM orders AS o
JOIN order_items AS i ON i.order_id = o.order_id
WHERE o.status = 'paid';
-- revenue 740, units 9
Units are right. Revenue is more than double, because order 1 has three line items, so its 120 is counted three times, and order 4’s 150 twice. This is the classic fan-out (sometimes called a fan trap): summing a column from the “one” side after joining to the “many” side. The fix is to aggregate the many side to the grain of the one side before joining:
SELECT sum(o.amount_eur) AS revenue, sum(i.units) AS units
FROM orders AS o
JOIN (SELECT order_id, sum(qty) AS units FROM order_items GROUP BY order_id) AS i
ON i.order_id = o.order_id
WHERE o.status = 'paid';
-- revenue 350, units 9
A model cannot see cardinality from DDL. Nothing in CREATE TABLE says that order_items.order_id repeats, so it has no signal that the first query is dangerous. The inflated number is also plausible: revenue went up, not to an absurd value.
3. Dates and time boundaries
“Revenue in September” invites BETWEEN:
SELECT sum(amount_eur) FROM orders
WHERE status = 'paid'
AND ordered_at BETWEEN '2026-09-01' AND '2026-09-30';
-- 200
The string '2026-09-30' becomes midnight at the start of 30 September, so order 4, placed that evening, is dropped. The correct form is a half-open interval, ordered_at >= '2026-09-01' AND ordered_at < '2026-10-01', which returns 350.
Dates fail in other ways too. “Last month” resolved with now() depends on the server’s time zone and on when the query runs, so a cached answer silently goes stale. “This week” depends on whether weeks start on Sunday or Monday; ClickHouse’s toStartOfWeek takes a mode argument for exactly that reason. Fiscal years, which rarely match the calendar, are invisible in the schema. Each choice is defensible, and a model makes it silently.
4. Null semantics that differ by engine
Ask “which customers have never ordered?”. The textbook anti-join, which a model trained mostly on Postgres and SQLite examples will write, is:
SELECT c.name
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.customer_id
WHERE o.order_id IS NULL;
-- 0 rows
On ClickHouse this returns nothing, because by default unmatched columns in an outer join are filled with the type’s default value (0 for a number, empty string for a string), not NULL. The JOIN documentation says the join_use_nulls setting controls this, and the settings reference lists its default as 0. The query is valid on both engines and correct on only one. Rewriting it as WHERE customer_id NOT IN (SELECT customer_id FROM orders), or setting join_use_nulls = 1, returns Dune.
Dialect gaps like this are where generic text-to-SQL is weakest, because the model’s priors come from engines with different semantics. If your warehouse is not Postgres, expect more of them. Our post on ClickHouse join performance covers other ways ClickHouse joins differ from row-store databases.
5. Silent approximation
Ask “how many distinct customers?” on ClickHouse and a model that knows the dialect may reach for uniq, because it is the idiomatic, fast choice:
SELECT uniq(number % 1000003) AS approx,
uniqExact(number % 1000003) AS exact
FROM numbers(5000000);
-- approx 1001943, exact 1000003
The ClickHouse docs describe uniq as calculating “the approximate number of different values”. An error of about 0.2% is fine for a traffic dashboard and wrong for a customer count that finance reconciles against billing. (count(DISTINCT x) is exact by default, because count_distinct_implementation defaults to uniqExact.) Whether approximation is acceptable is a business decision, and again it is not in the schema.
What grounding techniques improve text-to-SQL accuracy?
Every failure above has the same cause: information the model needs is not in the prompt. Grounding means putting it there, or better, taking the decision away from the model entirely. Here are the techniques, from weakest to strongest.
| Technique | Fixes | Leaves open |
|---|---|---|
| Schema pruning (retrieve only relevant tables) | Wrong-table picks in large schemas | Business rules, cardinality, dialect |
| Column descriptions and sample values | Cryptic names, enum values like 'paid' | Join grain, metric definitions |
| Business glossary and rules in the prompt | Some ambiguous metrics | Model may still ignore or misapply rules |
| Verified example queries (few-shot) | Common questions, dialect idioms | Questions unlike the examples |
| Execution checks (dry run, row counts, sanity bounds) | Syntax errors, empty results, wild numbers | Plausible wrong numbers |
| Semantic layer (model picks metric, layer writes SQL) | Metric, join, date and dialect logic | Questions outside the defined metrics |
Give the model less schema, with more meaning
Pasting a 900-table DDL into the prompt hurts more than it helps. Retrieve the 5 to 15 tables relevant to the question, and for each column include a one-line description, the distinct values for low-cardinality columns, and the declared grain of the table (“one row per order line”). Grain is the single most useful annotation, because it is what lets a model spot a fan-out.
Write the business rules down, then retrieve them
The ambiguous-metric failure is fixed only by stating the definition: “Revenue = sum of amount_eur for status = 'paid', excluding test accounts, months in UTC.” Keep these definitions in a glossary that an owner approves, and inject the relevant entries with each question. This also forces the organisation to agree on the definitions, which is often the real blocker. If the same metric already means different things on different dashboards, a metric drift audit will find where.
The limit of this approach is that the model still writes the SQL. It can read “exclude cancelled orders” and still forget the filter in a query with three CTEs.
Keep verified queries and use them as examples
Every query an analyst has checked is a training example for your domain. Store question-and-SQL pairs that a human verified, retrieve the closest ones for each new question, and include them in the prompt. This teaches dialect idioms (the NOT IN anti-join, half-open intervals) and the house style for common metrics. It helps most for questions that resemble past ones, which in practice is most of them.
Check the result, not just the syntax
Run EXPLAIN before executing to catch syntax and missing columns. After execution, check that the result is not empty, that row counts are within the expected order of magnitude, and that totals reconcile with a known figure where one exists (yesterday’s revenue from the finance dashboard, for example). These checks catch the loud failures. They do not catch 740 instead of 350, which is why they are a backstop, not a fix. The same principle appears in using LLMs for query root-cause analysis: give the model real signals from the engine, and verify before trusting.
Let a semantic layer write the SQL
The strongest technique changes the task. Instead of asking the model to write SQL, ask it to choose a defined metric, dimensions, a time grain and filters, then let a semantic layer compile the SQL from definitions a human reviewed. The model’s job shrinks from “write correct SQL against 900 tables” to “map this question to one of these 40 metrics”, which is a much easier problem.
Each failure above disappears by construction. The metric filter lives in the definition. The layer knows that order_items is many-to-one with orders and aggregates before joining, or refuses the combination. Date bucketing and time zones are fixed per metric. Dialect quirks are handled once in the compiler, by people who tested them.
dbt Labs’ 2026 benchmark shows both the strength and the limit. On an 11-question insurance benchmark, each question run 20 times, raw text-to-SQL with the full schema in the prompt scored 64.5% for both Claude Sonnet 4.6 and GPT-5.3-Codex. After adding three dbt models that join a few of the normalised tables together, text-to-SQL rose to 90.0% and 84.1%, and the semantic layer reached 98.2% and 100%. Before those models existed, the semantic layer answered none of the questions that needed too many joins. Two lessons: modelling the data helps both approaches, and a semantic layer only answers what it defines. The authors’ summary of the failure mode is the key argument: “It never silently returns wrong data.” When a question falls outside the defined metrics, the right behaviour is a refusal or a clarifying question, not a guess.
How to measure text-to-SQL accuracy on your own data
Public leaderboards tell you little about your warehouse. Build a small evaluation set instead:
- Collect 30 to 50 real questions from Slack threads, BI requests and dashboard titles. Include the vague ones.
- Write the correct answer for each, as a verified query and its result, signed off by the metric owner.
- Add questions that must be refused, ones your data cannot answer. A system that guesses on these is dangerous.
- Score on results, not SQL text. Two different queries can both be right. Compare the returned values, with a tolerance for floating point.
- Run each question several times. LLM output varies; a question answered right three times out of five is not reliable.
- Rerun on every change: new model, new prompt, new tables. Treat it as a regression suite.
Track two numbers separately: the share of answerable questions answered correctly, and the share of unanswerable questions correctly refused. The second matters as much as the first.
Where Goni fits
If your warehouse is ClickHouse, Goni is one option built around the semantic-layer approach: full disclosure, this is our product. Its AI Q&A cannot write free-form SQL against raw tables. The model returns a plan (metric, dimensions, time grain, filters), which is validated against the metrics and dimensions defined in a git-tracked YAML semantic layer and compiled to ClickHouse SQL. A question that does not map to a defined metric comes back as a clarifying response listing what can be asked. Approved business glossary terms are added to the prompt, the compiled SQL is shown under every chart, and a built-in evaluation harness scores both faithful answers and correct refusals against a question suite. The drawbacks are real: ClickHouse is the only warehouse Goni queries, it is not open source, and it is younger than the alternatives. There is a 14-day free trial if you want to test it on your own questions.
FAQ
How accurate is text-to-SQL?
It depends on the benchmark. Top systems score above 80% on BIRD, an academic benchmark that supplies hints. On enterprise-style benchmarks the figures fall sharply: 21.3% for an o1-preview agent on Spider 2.0 at publication, and 10.8% for GPT-5.2 agentic frameworks on BEAVER. Accuracy on your warehouse depends on your schema, business rules and grounding.
Why does AI get SQL wrong?
Mostly because the information it needs is not in the schema. Column names do not say which rows a metric excludes, which joins multiply rows, which time zone defines a month, or how your engine handles nulls. The model fills those gaps with plausible guesses, producing SQL that runs and returns a believable but wrong number.
How do you improve text-to-SQL accuracy?
Retrieve only relevant tables and annotate them with descriptions, sample values and grain. Inject approved metric definitions, and include verified example queries for similar questions. Check results after execution. The strongest step is a semantic layer: the model picks a defined metric and the layer compiles the SQL, so business logic is never generated.
Is a semantic layer better than text-to-SQL?
For defined business metrics, yes. In dbt Labs’ 2026 benchmark the semantic layer reached 98.2% to 100% against 84.1% to 90.0% for text-to-SQL on the same modelled data. But it only answers questions about metrics it defines. Many teams use both: the semantic layer for governed numbers, text-to-SQL for exploration with human review.
Can LLMs hallucinate in analytics?
Yes, and in analytics a hallucination usually looks like a valid query with wrong logic rather than invented text: a missing filter, a fan-out join, a wrong date range. The answer is a believable number. Grounding the model in defined metrics, showing the generated SQL, and refusing questions outside the defined scope are the main defences.