Drills D06

Text-to-SQL analyst assistant

Design an assistant that lets business users ask questions in plain English about the company's data warehouse and get back correct numbers, a chart and the SQL it ran. How do you make it correct and safe?

45 minutes · revise 18.03 · 13.04 · 21.13 · 33.09 · 19.09 · 20.08 · 15.14

Text-to-SQL looks like a solved demo and is hard in production for one reason: a wrong query returns a confident, well-formatted wrong number. The interviewer wants to hear how you ground the model in the real schema and the company’s metric definitions, how you validate and sandbox the SQL before it runs, and how you evaluate on execution results rather than SQL text.

Clarify and scope

Baseline architecture

 question ─► auth (user, role, region) ─► rate limit
   ─► classify: answerable? ambiguous? ─► clarify question if ambiguous
   ─► resolve dates in code ("last quarter" → explicit range, fiscal calendar, timezone)
   ─► schema linking:
        retrieve tables/columns from a catalog index
        (names, descriptions, sample values, join keys, popularity, deprecated flags)
        + metric definitions from the semantic layer
        + 3-5 verified question→SQL examples (retrieved by similarity)
   ─► generate: structured {sql, tables_used, assumptions[], chart_hint}
   ─► validate in code:
        parse (SQL parser) · single SELECT only · tables in allowlist for role
        · no PII columns unless permitted · LIMIT added · EXPLAIN cost below cap
   ─► execute on read replica / warehouse as the USER's role (row-level security),
        statement timeout, bytes-scanned cap
        error? ─► feed error + schema back, retry at most 2 times
   ─► result checks: empty? suspicious magnitudes? ─► summarise (small model) + chart
   ─► show answer + assumptions + SQL ─► feedback (correct / wrong + fix)
   analyst-verified pairs ─► example store + eval set

See the text-to-SQL section for query construction more broadly.

Key choices and trade-offs

Schema linking is the core problem. 15,000 columns of DDL is far too much to put in every prompt, and most wrong answers come from picking the wrong table or join, not bad SQL syntax. Build a catalog: each table and column with a human-written description, example values, foreign keys and how often analysts actually query it. Retrieve the top 10 or so tables by hybrid search over that catalog, then expand along known join keys. Deprecated tables are excluded from the index entirely. Curating the catalog is the highest-leverage work in the project, and it is mostly not AI work.

Semantic layer over raw SQL where possible. If “revenue” and “active customer” are defined once in a metrics layer, have the model choose metrics, dimensions and filters, and let the layer generate SQL. That removes a whole class of errors (different definitions of the same metric) at the cost of only answering questions the layer covers. Use raw SQL generation as the fallback for the long tail, with a visible “this used custom SQL” label.

Verified examples. A store of question and SQL pairs that analysts have approved, retrieved as few-shot examples. It is the cheapest way to teach company conventions (fiscal year, test accounts to exclude, IST timezone), and it grows from user feedback.

Dates in code, not in the model. Relative dates are a classic failure: “last quarter” depends on the fiscal calendar, “this week” on the timezone and week start. Resolve them in code before generation and pass explicit ranges.

Ask, don’t guess. If two tables could answer “how many customers”, or the metric is undefined, ask one clarifying question with the options. Guessing silently is how wrong numbers reach a board deck.

Structured output. The model returns SQL plus the tables it used and the assumptions it made, under a schema validated in code (Pydantic/Zod validation). The assumptions are shown to the user; they are how a non-SQL user catches a wrong interpretation.

Evals

Guardrails and fallbacks

Observability and cost

Trace per question: retrieved tables, examples used, generated SQL, validation result, retries and error messages, rows returned, bytes scanned, query time, tokens. Dashboards: execution success rate, retries per question, clarification rate, thumbs-down rate by table, warehouse cost from assistant queries, p95 end-to-end time. The table-level thumbs-down view tells you which catalog descriptions to fix next.

The numbers

Prompt size.

full schema   15,000 columns × ~15 tokens   ≈ 225K tokens (does not fit usefully)
linked schema ~10 tables × ~30 columns × ~15 tokens ≈ 4.5K tokens
examples      4 × ~300                      ≈ 1.2K tokens
rules + metric definitions (cacheable)      ≈ 1.5K tokens
input per generation                        ≈ 7K tokens; output ≈ 300

Cost per 1K questions (P in dollars per million tokens; check current prices):

generation  1.3 calls avg (retries) × (7 × P_in + 0.3 × P_out)
summary     2 × P_in_small + 0.2 × P_out_small    (results ~2K tokens in)
LLM total   ≈ 9.1 × P_in + 0.39 × P_out + summary
warehouse   1,000 × average bytes scanned × warehouse price per byte

Warehouse cost can exceed LLM cost if queries scan large tables, which is why the bytes-scanned cap matters.

Load. 5,000 questions over a 10-hour office day is 5,000 / 36,000 ≈ 0.14 questions per second; plan for perhaps 1 per second at peak. LLM throughput is not the constraint; warehouse concurrency and query time are.

Latency budget (targets). Auth, classify and date resolution 200 to 500 ms; schema retrieval 100 to 300 ms; generation 1 to 3 s; validation and EXPLAIN 200 to 500 ms; execution anywhere from 0.5 s to tens of seconds; summary 1 to 2 s. A retry adds a generation and an execution. Most of the variance is the query, not the model.

Follow-ups they will ask

How to bring in your own work

You have not built a text-to-SQL system, and none of the example projects has an LLM generating SQL, a SQL parser in the loop, or a semantic layer. Say so, then point to the pieces that transfer.

esc

Narrow with repo:jm layer:eval q:naive mine · ↑↓ to move, enter to open