Every "chat with your data" demo looks the same. Someone types "What were sales by region last quarter?", the model writes a tidy GROUP BY, a chart appears, everyone nods.
Then you point it at a real warehouse and ask something ordinary: "How many active customers did we have last month?" It runs. It returns a number. The number is wrong, and nothing about it looks wrong.
That's the failure mode worth designing around. A query that errors out is annoying. A query that runs and returns a plausible, incorrect number ends up in a slide deck.
The ambiguity isn't in the SQL
Take that question apart and look at how many decisions are hiding in it:
- "Active": had a billable service on the last day of the month? Used the service at least once during the month? Not cancelled?
- "Customers": accounts, or the people or lines under an account? Do test and employee accounts count?
- "Last month": the calendar month, or the trailing 30 days? In which time zone?
- Which table: the CRM's account table, the billing snapshot, or the curated model the finance team reconciles against?
A strong model can write flawless SQL for every one of those interpretations. Writing the SQL isn't the hard part. The hard part is that the right answer depends on definitions that live in people's heads, in a wiki page, or in a dashboard's calculated field. None of that is in the schema you pasted into the prompt.
If two analysts on your team would write different SQL for the same question, a model will too. It just won't tell you which one it picked.
Give it definitions, not a schema dump
The usual first move is to stuff CREATE TABLE statements into the context window. That tells the model what columns exist, not what they mean, and a big warehouse will have three tables that could plausibly answer any question.
What helps is a semantic layer: a small, reviewed set of metric definitions that says exactly how each business number is calculated. It doesn't need a vendor. A YAML file in a repo works:
# metrics.yml
metrics:
active_customers:
description: >
Accounts with at least one billable service in an active state on the
snapshot date. Excludes test and employee accounts.
table: analytics.fct_account_daily
time_column: snapshot_date
snapshot: true # measured at a point in time, not summed over a range
expression: COUNT(DISTINCT account_id)
filter: "service_status = 'active' AND account_type NOT IN ('test', 'employee')"
dimensions: [region, plan_family, sales_channel]
new_activations:
description: Services activated during the period, any account type except test.
table: analytics.fct_activations
time_column: activation_date
snapshot: false
expression: COUNT(*)
filter: "account_type <> 'test'"
dimensions: [region, plan_family, sales_channel]Notice what's in there that a schema can't tell you: the exclusions, the point-in-time versus over-a-range distinction, and which table is the blessed one. Those are exactly the things the model was guessing at.
Let the model pick, and let code write the SQL
Once you have definitions, stop asking the model for SQL at all. Ask it to choose from a menu: which metric, which dimensions, which time period. Use your provider's structured output (JSON mode or tool calling) so you get back something like this:
{
"metric": "active_customers",
"dimensions": ["region"],
"start": "2026-11-01",
"end": "2026-11-30"
}Then deterministic code turns that into SQL:
from datetime import date
import yaml
METRICS = yaml.safe_load(open("metrics.yml"))["metrics"]
def compile_query(q: dict) -> str:
if q["metric"] not in METRICS:
raise ValueError(f"Unknown metric: {q['metric']!r}")
m = METRICS[q["metric"]]
dims = q.get("dimensions", [])
for d in dims:
if d not in m["dimensions"]:
raise ValueError(f"{d!r} isn't a valid dimension for {q['metric']}")
# Parsing the dates both validates them and keeps model text out of the SQL.
start = date.fromisoformat(q["start"])
end = date.fromisoformat(q["end"])
if start > end:
raise ValueError("start is after end")
if m["snapshot"]:
time_filter = f"{m['time_column']} = DATE '{end}'"
else:
time_filter = f"{m['time_column']} BETWEEN DATE '{start}' AND DATE '{end}'"
where = " AND ".join(f"({c})" for c in [m.get("filter"), time_filter] if c)
select = ", ".join([*dims, f"{m['expression']} AS {q['metric']}"])
group_by = f"\nGROUP BY {', '.join(dims)}" if dims else ""
return f"SELECT {select}\nFROM {m['table']}\nWHERE {where}{group_by}"This gives up some flexibility, and that's the point:
- The model can't invent a definition. It can only pick a metric someone reviewed.
- Bad picks fail loudly. An unknown metric or dimension raises an error instead of running.
- Nothing the model writes goes into SQL as raw text. Names are checked against the YAML and dates are parsed, so there's nothing to inject.
- You can show your work. "Active customers (accounts with an active billable service, excluding test and employee accounts) on Nov 30, by region" is an answer someone can check.
The trade-off is coverage. Questions outside the menu can't be answered. I'd take that over an answer of unknown quality. The gaps also make a useful backlog: the questions people ask that you can't answer show you which metrics to define next.
Test answers, not queries
You need an eval set before you trust any of this, and it should compare results, not SQL text. Two queries can look completely different and return the same correct rows, or look nearly identical and return different ones.
Keep a CSV of real questions next to the query a person verified for each:
import csv
from collections import Counter
def run_evals(path, ask, run_sql):
"""ask(question) -> structured query dict; run_sql(sql) -> list of row tuples."""
with open(path) as f:
cases = list(csv.DictReader(f))
failures = []
for case in cases:
try:
got = run_sql(compile_query(ask(case["question"])))
except Exception as e:
failures.append((case["question"], f"error: {e}"))
continue
expected = run_sql(case["expected_sql"])
# Compare as multisets so row order doesn't matter.
if Counter(got) != Counter(expected):
failures.append((case["question"], "wrong result"))
print(f"{len(cases) - len(failures)}/{len(cases)} passed")
return failuresA few rules for the eval set that I'd treat as non-negotiable:
- Use questions people actually asked, phrased the way they asked them, typos and all. Questions you write yourself are too clean.
- Include questions it should refuse. "What will churn be next quarter?" shouldn't come back as a
SELECT. - Re-run it on every change: new metric, new prompt, new model version. That's what makes model upgrades a non-event instead of a leap of faith.
Make "I'm not sure" a valid answer
Add an explicit way out to the structured output, something like {"clarify": "Do you mean accounts or individual lines?"}. Prompt for it, and put ambiguous questions in your eval set that expect a clarifying question back.
A tool that asks one good follow-up question earns more trust than one that always answers. People are fine with "which one did you mean?" What they won't forgive is the wrong number turning up in front of their VP.
Where raw text-to-SQL is fine
None of this means generated SQL is useless. For an analyst who reads SQL, letting a model draft a query against the raw schema is a real time saver: they review it before running it and know when it's wrong.
The line I'd draw is who checks the output. If the person asking can read and verify SQL, let the model write SQL. If they can't, and that's the whole promise of "ask your data anything", the model should only be choosing between definitions that someone who can verify has already written down.