Text-to-SQL: Natural Language to Database Queries
Module: Natural Language Processing | Difficulty: Advanced
What You'll Learn
- 1Break text-to-SQL into intent parsing, schema linking, and query generation
- 2Compute execution accuracy and explain how it differs from exact match
- 3Link question mentions to tables and columns with similarity ranking
- 4Compare supervised parsers with prompted LLM pipelines on Spider
Text-to-SQL translates a question in natural language into an executable database query. It is the cleanest example of semantic parsing, because the target language is formal, its semantics are defined by a database engine, and wrong answers are checkable by running the query.
The Spider Benchmark
Spider (Yu et al., 2018) remains the reference test: 10,181 questions paired with 5,693 unique SQL queries over 200 databases spanning 138 domains. Eleven annotators spent roughly 1,000 person-hours building it, and the schemas average 27.6 columns and 8.8 foreign keys each, so most queries require joins across tables rather than single-table lookups.
Evaluation executes the predicted query and compares results with the gold results:
| System | Spider test EX | Setting |
|---|---|---|
| RESDSQL-3B with NatSQL | 79.9 | fine-tuned encoder-decoder |
| C3 with ChatGPT | 82.3 | prompted correction |
| DIN-SQL with GPT-4 | 85.3 | decomposed in-context learning |
| DAIL-SQL with GPT-4 | 86.6 | example selection plus self-consistency |
| DAIL-SQL with GPT-4o | 5.68 | Spider 2.0-lite enterprise schemas |
The gap in the last row is the point of the lesson: a system at 86.6 on Spider falls to 5.68 on enterprise-style schemas with abbreviations, huge column counts, and nested queries.
Two ideas account for most of the recent gain. Decomposition breaks the problem into linking, query drafting, and correction, which took GPT-4 from 67.4 with naive few-shot prompting to 85.3. Self-consistency then samples several queries and keeps the majority:
That voting step is small but real: DAIL-SQL reports 86.2 before self-consistency and 86.6 after it.
Schema Linking
Before generation, question spans must be mapped to schema elements. This is a ranking problem over columns and tables:
for a mention in the question. The database also supplies structure through foreign keys, which constrain which tables can be joined:
Modern pipelines add a grammar so that only syntactically valid partial queries can be extended, which is the idea behind constrained decoding and PICARD-style parsing during generation.
where is the set of tokens that keep the prefix inside the SQL grammar.
Worked Code
import re
SCHEMA = {
"students": ["id", "name", "grade", "gpa"],
"courses": ["id", "title", "credits"],
"enrollments": ["student_id", "course_id", "term"],
}
def link_columns(question):
words = set(re.findall(r"[a-z0-9]+", question.lower()))
ranked = []
for table, columns in SCHEMA.items():
for col in columns:
overlap = len(words & {table, col} | words & set(col.split("_")))
ranked.append((overlap, table, col))
ranked.sort(reverse=True)
return [r for r in ranked if r[0] > 0]
for question in ["Which students have a high gpa",
"list courses credits for the term"]:
hits = link_columns(question)
print(question)
for overlap, table, col in hits[:3]:
print(f" {overlap} {table}.{col}")
The second program evaluates predictions by executing them, so execution accuracy and exact match are computed side by side on the same data.
import re
DB = {
"students": [
{"id": 1, "name": "ada", "grade": 95, "gpa": 3.9},
{"id": 2, "name": "lin", "grade": 88, "gpa": 3.4},
{"id": 3, "name": "kim", "grade": 71, "gpa": 2.7},
],
"courses": [
{"id": 10, "title": "databases", "credits": 3},
{"id": 11, "title": "networks", "credits": 4},
],
}
PATTERN = re.compile(
r"select\s+(?P<col>[\w.]+)\s+from\s+(?P<table>\w+)"
r"(?:\s+where\s+(?P<where>\w+)\s*(?P<op><=|>=|<|>|=)\s*(?P<val>[\w.]+))?",
re.I,
)
def execute(sql):
m = PATTERN.search(sql.strip())
if not m:
raise ValueError("unsupported sql: " + sql)
table, col = m.group("table"), m.group("col")
rows = DB[table]
if m.group("where"):
where, op, raw = m.group("where"), m.group("op"), m.group("val")
val = float(raw) if re.match(r"^\d+(\.\d+)?$", raw) else raw
checks = {"=": lambda a: a == val, "<": lambda a: a < val,
">": lambda a: a > val, "<=": lambda a: a <= val,
">=": lambda a: a >= val}
rows = [r for r in rows if checks[op](r[where])]
return sorted(r[col] for r in rows)
def evaluation(pairs):
exact = sum(1 for pred, gold in pairs if pred.strip() == gold.strip())
ex = sum(1 for pred, gold in pairs if execute(pred) == execute(gold))
n = len(pairs)
return {"EM": exact / n, "EX": ex / n, "n": n}
pairs = [
("select gpa from students where grade > 80",
"select gpa from students where grade > 80"),
("select gpa from students where grade >= 80",
"select gpa from students where grade > 80"),
("select title from courses where credits = 3",
"select credits from courses where credits = 3"),
]
print(evaluation(pairs))
for sql, _ in pairs:
print(sql, "->", execute(sql))
Real-World Applications
- Business intelligence: natural language interfaces to warehouses, where Spider 2.0-lite results show enterprise schemas remain the hard case.
- Analytics self-service: analysts ask questions without writing joins across a schema with 27.6 columns per table on average.
- Data validation: generated queries act as executable checks over newly loaded tables.
- Support tooling: ticket triage queries run against CRM databases with schema linking restricted to a small table subset.
đĄExecution accuracy can hide errors
Common Mistakes
Evaluating by string match alone
Fix: Report execution accuracy as primary and exact match as a secondary number
Skipping schema linking
Fix: Link mentions to columns first, since wrong columns cannot be repaired by decoding
Testing only on Spider
Fix: Include BIRD or Spider 2.0-lite, where GPT-4 falls from 46.35 to single digits
Best Practices
- Publish results by query difficulty, not only the overall mean
- Report both EX and EM, and state how ties in result sets are handled
- Evaluate schema linking separately from generation
Key Takeaways
- Spider holds 10,181 questions, 5,693 queries, and 200 databases over 138 domains
- Execution accuracy reached 86.6 with DAIL-SQL and GPT-4 on Spider test
- Equivalent queries that differ in text explain the gap between EX and EM
- Spider 2.0-lite drops the same system to 5.68, so schema realism is still unsolved
Frequently Asked Questions
Why use execution accuracy instead of exact match?
Because SQL is not canonical: filters can be written with different operators that yield the same rows, and subqueries can be flattened. Execution compares results, which is what users care about, though it needs the gold database and can match accidentally on small tables.
What makes enterprise schemas harder?
Abbreviated column names, dozens of candidate tables, and deep nesting. DAIL-SQL scores 86.6 on Spider but 5.68 on Spider 2.0-lite, which was designed to reproduce those conditions.
Where do LLM pipelines help most?
In decomposition: DIN-SQL and DAIL-SQL split linking, query drafting, and correction into steps with example retrieval, moving GPT-4 from 67.4 with naive few-shot prompting to 85.3 and 86.6.
Interview Questions
Q1: How do you evaluate a text-to-SQL system offline?
Execute predicted and gold queries on the same database and compare result sets, also reporting exact match
Q2: What role do foreign keys play in generation?
They define the join graph, so a connected table set needs exactly k minus 1 joins
Q3: How would you debug a system that generates valid but wrong SQL?
Check schema linking first, then clause-level execution of the predicted query against gold intermediates