Expert about 6 h
The picture
01
Question
business language
02
Ground
schema, glossary
03
Generate SQL
read-only
04
Validate
parse, allow-list, LIMIT
05
Execute
capped, timed
06
Reflect
check, retry, cite
The shape of the problem
Business users ask in their own words ("which regions missed target last quarter?"). An agent must translate that into a correct query against a schema it has never seen in full, run it safely, and explain the result honestly. Three things decide whether this works in production: grounding, safety and verification.
Grounding: give the model the right slice of the schema
A real warehouse has thousands of columns. Do not paste it all.
- Keep a catalogue: table and column descriptions, business glossary ("active customer = purchase in last 90 days"), join keys, and a few example queries.
- Retrieve the relevant tables and examples for each question (the same retrieval techniques as RAG, over the catalogue).
- Put only that slice in the prompt, with sample values for ambiguous columns.
Governance as code helps: keep the catalogue and permitted tables in version control, reviewed like any other change.
Safety: validate by parsing
String checks ("does it contain DROP?") are bypassable. Parse the SQL and inspect the tree.
import sqlglot
from sqlglot import exp
WRITE_NODES = (exp.Insert, exp.Update, exp.Delete, exp.Drop, exp.Create, exp.Alter, exp.Command, exp.Merge)
class SQLRejected(ValueError):
pass
def validate_readonly(sql: str, allowed_tables: set[str], dialect: str = "postgres", max_rows: int = 1000) -> str:
try:
trees = sqlglot.parse(sql, dialect=dialect)
except sqlglot.errors.ParseError as e:
raise SQLRejected(f"SQL does not parse: {e}")
if len(trees) != 1 or trees[0] is None:
raise SQLRejected("Send exactly one statement.")
tree = trees[0]
if not isinstance(tree, (exp.Select, exp.Union)):
raise SQLRejected("Only SELECT queries are allowed.")
if tree.find(*WRITE_NODES):
raise SQLRejected("Write operations are not allowed.")
used = {t.name.lower() for t in tree.find_all(exp.Table)}
forbidden = used - {t.lower() for t in allowed_tables}
if forbidden:
raise SQLRejected(f"Tables not permitted: {sorted(forbidden)}. Permitted: {sorted(allowed_tables)}")
if not tree.args.get("limit"):
tree = tree.limit(max_rows)
return tree.sql(dialect=dialect)
Parsing is one layer. Also connect with a read-only database role limited to the permitted schemas, set a statement timeout, and cap returned rows. Never rely on one layer.
The tool and the repair loop
@tool
def run_sql(sql: str) -> str:
"""Run ONE read-only SELECT against the analytics warehouse. Returns up to 50 rows as JSON plus the total row count."""
safe = validate_readonly(sql, ALLOWED_TABLES) # raises SQLRejected with a teaching message
rows = db.fetch(safe, timeout_s=30)
return json.dumps({"rows": rows[:50], "total_rows": len(rows)}, default=str)
Because the agent loop returns tool errors as text, a rejection ("Tables not permitted: ['payroll']. Permitted: [...]") or a database error becomes the next prompt and the model usually corrects itself. Cap repair attempts at two or three.
Verification: do not trust a confident wrong number
- Reflection after execution: ask a checker, with the question, the SQL and a sample of the result, whether the result plausibly answers the question (right grain, right filters, sensible magnitude). Re-run low-confidence cases with a refined query.
- Consistency: generate the query twice independently; if results differ, flag it.
- Show your work: return the SQL and the tables used so an analyst can audit it.
- Evaluate on execution accuracy: run gold queries and compare result sets, not SQL strings.
Cost and latency
Route simple questions down a fast path (a single query generation, no planner) and reserve multi-agent decomposition for cross-domain questions. Cache the schema context and measure tokens per question.
Common mistakes
- Blocking
DROPwith a regex while allowing a stacked statement. - Handing the agent one connection with write rights "for convenience".
- Reporting a number without the filters that produced it.
Exercises
- Write 15 adversarial queries (stacked statements, comments, CTEs that write, forbidden tables) and show your validator rejects each.
- Build a 30-question evaluation set over a sample database and report execution accuracy before and after adding retrieval of schema context.
You are done when you can…
- Validate model-written SQL by parsing it, not by pattern-matching
- Provide just enough schema context for accurate queries on a large catalogue
- Add a confidence or consistency check and a bounded repair loop