Design: text-to-SQL analytics assistant
Retrieve relevant metrics, tables and verified queries; ask when ambiguous; generate a semantic-layer query or SQL; validate it deterministically; run it as the user; and show the result with its SQL and assumptions.
Analogy: A new analyst on day one: checks the team's metric glossary and old queries before writing SQL, asks ‘which revenue?’ instead of guessing, and shows their query so a senior can spot the bad join.
Fundamentals you'll use
How it works
- Load is low (~2 questions/s at peak), so correctness and warehouse cost dominate, not serving.
- Retrieve tables, then their columns, plus a value index so ‘EMEA’ maps to a real literal.
- The worst failure is a plausible wrong number; a semantic layer writes the joins and removes fan-out double counting.
- Run as the user's own read-only identity, with a bytes cap: one 10 TB scan costs ~$57.
- Grade by execution accuracy on ~300–500 golden questions: compare result sets, never the SQL text.
Check yourself
Answer to mark it learned; your answers aren't scored.
A director asks for net revenue by region and gets a number well above the official dashboard. The generated SQL joins orders to line_items, then sums order_total. What is the most robust fix?
Go deeper
Full explanation
Requirements
Functional: business users ask analytics questions in plain language (‘net revenue by region last quarter vs a year ago’) and get a table or chart, the SQL that produced it, and the assumptions made. Follow-ups refine the previous answer; ambiguous questions get one clarifying question.
Non-functional: correctness first; read-only access that respects each user's row- and column-level permissions; p50 under ~10 s; a per-query warehouse cost cap; every query logged for audit.
What I'd ask first:
- Who asks: analysts who read SQL, or executives who never will?
- Is there a semantic layer or governed metric definitions (dbt, LookML, Cube), or only raw tables?
- How big and how documented is the schema: 50 tables or 5,000?
- Do permissions differ by user today, and are they enforced in the warehouse?
- What does a query cost, and what is the latency budget?
Highest-cost failure: a plausible, wrong number (revenue double-counted by a fan-out join, or ‘active users’ defined differently from the official metric) that lands in a board deck. It is silent and it looks authoritative.
High-level design
Offline: index a catalog of tables, columns, descriptions, join keys, sample values of low-cardinality columns, and the semantic layer's metrics. Mine the query log for analyst-verified queries, each with a short description, to use as Zero-shot vs few-shot prompting examples and to seed the golden set.
Online, per question:
- Retrieve: Hybrid search & RRF over the catalog for the relevant metrics, tables and columns, a value index (‘EMEA’ →
region_code), and the 3 most similar verified queries, all filtered to what this user may see (Metadata filters & permission-aware retrieval). - Clarify: if the question maps to two metrics or lacks a needed filter, ask; for minor gaps, state the assumption instead.
- Generate: prefer a semantic-layer query (metric, dimensions, filters) as Structured outputs & JSON mode, and let the layer compile the joins. Fall back to raw SQL for exploratory questions, labeled unverified.
- Validate: parse, allow a single SELECT, check tables against the user's allowlist, add a LIMIT, and cap bytes scanned with EXPLAIN or a dry run.
- Execute: with the user's identity, so warehouse row-level security applies, under a statement timeout. On an error, feed the message back and retry at most twice.
- Present: result, SQL, metric definitions, assumptions and data freshness. An analyst's ‘verified’ click adds the query to the example bank.
Code The deterministic gate between the LLM and the warehouse
import sqlglot
from sqlglot import exp
MAX_ROWS = 10_000
WRITES = (exp.Insert, exp.Update, exp.Delete, exp.Merge, exp.Create, exp.Drop)
def validate(sql: str, allowed: set[str], dialect: str = "snowflake") -> str:
stmts = sqlglot.parse(sql, read=dialect) # raises on syntax errors
if len(stmts) != 1:
raise ValueError("exactly one statement")
tree = stmts[0]
if not isinstance(tree, (exp.Select, exp.Union)) or tree.find(*WRITES):
raise ValueError("read-only SELECT only") # the DB role is read-only too
ctes = {c.alias_or_name.lower() for c in tree.find_all(exp.CTE)}
for t in tree.find_all(exp.Table):
name = f"{t.db}.{t.name}".lower()
if t.name.lower() not in ctes and name not in allowed:
raise ValueError(f"table not allowed for this user: {name}")
if not tree.args.get("limit"):
tree = tree.limit(MAX_ROWS)
return tree.sql(dialect=dialect)
def run(sql: str, user, max_gb: float = 50):
safe = validate(sql, allowed_tables(user))
if dry_run_bytes(safe, user) > max_gb * 1e9: # EXPLAIN / dry run
raise ValueError("query too expensive: add filters")
return execute_as(user, safe, timeout_s=60) # warehouse RLS appliesReal example
A sales director asks: ‘How did revenue in EMEA do last quarter vs the same quarter last year?’ Retrieval returns two candidate metrics, gross_bookings and net_revenue, plus the region dimension and 3 similar verified queries. That is a real ambiguity, so the assistant asks: ‘Net revenue (after refunds) or gross bookings?’ The user picks net. The LLM emits a semantic-layer query (metric net_revenue, filter region = EMEA, two fiscal quarters) that compiles to SQL over 3 tables. Validation passes and the dry run estimates 3.1 GB scanned, under the 50 GB cap. It runs as the director's role in 2.4 s: $41.2M vs $36.8M, +12.0%. The answer shows the SQL, the metric definition and the assumptions (fiscal quarters, USD at monthly average FX). About 7 s end to end, plus the user's reply.
Trade-offs +4 · −4
+ You gain
- The semantic-layer path matches the dashboards, because it uses the same metric definitions.
- Validation and row-level security live in deterministic layers, so a bad generation can't write, leak or run up the bill.
- Showing the SQL, definitions and assumptions lets users catch the errors that remain.
- The verified query bank improves accuracy every week analysts use it.
− You pay
- Needs a curated semantic layer and a documented catalog; the real cost is data work, not the model.
- The raw-SQL fallback stays error-prone on long-tail questions, with silent wrong joins.
- Clarifying questions add a turn; asking too often drives users away.
- The golden set needs analyst time to build and to maintain as schemas change.
Use it when
Many people who don't write SQL asking recurring questions over a governed warehouse with defined metrics, with analysts available to verify answers and curate examples.
Avoid it when
An undocumented schema with no metric definitions (build the semantic layer first), figures that must be audited without a human in between, or anything that writes data.
Numbers to know 6
- Load: assume 2,000 users × 10 questions per workday = 20k/day; over ~8 working hours ≈ 0.7/s, peaks ~2/s.
- Tokens per question: ~3k schema + ~1.5k few-shot + ~1.5k instructions ≈ 6k in and ~0.4k out, × ~1.3 calls for clarifications and retries.
- LLM: 440k questions/month (22 workdays) → ~3.4B input + ~0.23B output tokens; at an assumed $2/M in and $8/M out ≈ $6.9k + $1.8k ≈ $9k/month.
- Warehouse guard: BigQuery on-demand is ~$6.25 per TiB scanned, so a full scan of a 10 TB table ≈ $57; a 50 GB per-query cap bounds the worst case at ~$0.30.
- Latency: retrieval ~0.2 s + generation 2–4 s + validation and dry run ~0.5 s + execution 1–5 s ≈ 4–10 s; each self-correction round adds ~3 s.
- Spider 2.0 (real enterprise schemas): the authors' code agent on o1-preview solved only ~21% of tasks, vs ~91% on Spider 1.0 and ~73% on BIRD (Lei et al., 2024).
Common pitfalls 4
- Enforcing access in the prompt: ‘only show the user's region’ is a suggestion, not a control. Execute as the user so warehouse row-level security applies.
- Grading by SQL string match: it fails correct alternatives and passes near-misses. Compare executed result sets on a pinned data snapshot.
- Fan-out joins: joining orders to line items and then summing order totals double-counts revenue. Route metric questions through the semantic layer and sanity-check totals against the official dashboard.
- A stale catalog: a renamed column or deprecated table breaks retrieval silently. Re-index on every schema deploy and re-run the golden set.
Interview questions 3
Answer out loud first, then reveal.
How do you stop it from returning a confidently wrong number?Show answer
Layers, because no single one is enough. Metric questions go through the semantic layer, so definitions and joins come from the data team, not the model. Real ambiguity gets a clarifying question; minor gaps get a stated assumption. Results get sanity checks (empty, NULL, a 10× jump vs the previous period), and every answer shows its SQL, metric definition and assumptions, labeled verified or unverified. Then I measure: execution accuracy on a golden set by question type, and how often analysts edit the SQL in production. The trade-off is friction: each clarifying question costs a turn, so I only ask when the readings would give different numbers.
The warehouse has 5,000 tables. How do you fit the schema in the context?Show answer
I don't. I retrieve in two stages: tables first, ranked by description match, query-log popularity and co-occurrence with similar verified queries; then only the relevant columns of those tables, plus join keys and a value index for literals. That keeps context around 3–5k tokens. Often I route by domain first, finance vs product, to shrink the space. I measure retrieval recall separately, whether the gold query's tables were retrieved, because the model can't use a table it never saw. Same lesson as RAG: fix recall before blaming generation.
How do you handle row-level security?Show answer
In the warehouse, never in the prompt. Queries execute with the user's identity, by OAuth pass-through or a mapped role, so the existing row-level policies and column masking apply to whatever SQL the model writes. The validator adds a table allowlist and a read-only check as defense in depth. Then I scope everything around the query too: catalog retrieval only shows tables the user can see, few-shot examples are filtered the same way, and the result cache is keyed by role. Otherwise schema names, example queries or cached numbers leak across users.
Deep dive 5
Schema & context retrieval
A warehouse with 5,000 tables does not fit in a prompt, and dumping 200 tables hurts accuracy anyway. Retrieve in two stages: tables first (descriptions, owners, query-log popularity, deprecation flags), then only their relevant columns, keeping context to ~3–5k tokens. Add a value index for low-cardinality columns so ‘EMEA’ or ‘churned’ map to real literals instead of guessed ones. Join keys and known-good join paths go in as facts. The query log is your best few-shot source: analyst-verified (description, SQL) pairs, retrieved by similarity to the question. Measure retrieval on its own (were the golden query's tables retrieved?), because generation cannot use a table it never saw (Evaluating RAG). Re-index on every dbt deploy, or a renamed column fails silently.
Generation strategy
Prefer the semantic layer. When a question maps to governed metrics, the LLM only picks metric, dimensions, filters and time grain as structured output, and the layer (dbt MetricFlow, LookML, Cube) writes the SQL with the right joins and aggregation. That removes fan-out double counting and definition drift, the two errors users cannot see. Raw SQL is the fallback for exploratory questions: a strong model, the retrieved schema plus few-shot, and an answer labeled unverified. Self-correction: on a database error, return the error text and retry at most twice; on a suspicious result (0 rows, NULL totals, 10× the last period), ask the model to recheck its filters. A small, fast model handles routing and ambiguity detection (Model routing & cascades).
Validation & security
The LLM proposes; deterministic layers authorize. Execute with the user's own identity (OAuth pass-through or a mapped role) so the warehouse's row-level security and column masking apply; never a superuser service account with ‘only show their region’ in the prompt (Multi-tenant isolation in AI apps). The role is read-only regardless. The validator parses in the warehouse's dialect, allows a single SELECT, rejects any write or system table, enforces the user's table allowlist, injects a LIMIT, and caps bytes scanned with EXPLAIN or a dry run plus a statement timeout. Scope retrieval, few-shot examples and any result cache by permission too, or schema names and cached numbers leak across users. Treat data values shown to the model as untrusted input (Prompt injection (direct & indirect)).
Evaluation
Grade by execution accuracy: run the generated and the gold SQL and compare result sets, ignoring column order and row order (unless there is an ORDER BY), with a tolerance for floats. Exact SQL match is useless: many correct queries look different, and a wrong one can look almost right (Code-based graders & assertions). Build a golden set of ~300–500 questions from verified queries, sliced by difficulty (joins, window functions, time logic) and by domain, plus ambiguous questions where the correct output is a clarifying question. Pin a data snapshot or compare against frozen results, or data changes will look like regressions. Online, track the verified rate, how often users edit the SQL, re-asks and thumbs-down, and run the golden set in CI on every prompt, model or catalog change (Evals in CI/CD & release gates).
Scale, latency & cost
Load is low (~2 questions/s at peak), so correctness and warehouse cost dominate, not serving. Latency budget ~4–10 s: retrieval ~200 ms, generation 2–4 s, validation and dry run ~0.5 s, execution 1–5 s; a self-correction round adds ~3 s, so stream progress (‘running query…’) to the UI (Streaming responses (SSE)). The model bill is small (~$9k/month at the volume below). The real danger is one unbounded scan: a full pass over a 10 TB table costs ~$57 on BigQuery on-demand, the token cost of ~3,000 questions, hence the bytes cap. Cache results keyed by normalized query, user role and data freshness, and answer repeated questions from the verified bank. Prompt caching covers the fixed instructions.