Text-to-SQL Agents and Schema Linking
Most wrong queries start before any SQL is written, when the agent picks the wrong tables or misreads what a column means.
A reliable text-to-SQL agent retrieves only the relevant schema and meaning, generates a query with verified examples for guidance, validates it before running, executes it with a read-only, limited identity, and checks the result before answering. Schema linking, which means connecting words in a question to tables, columns and values, is where much of the accuracy is won or lost.
What you will learn: the parts of a SQL agent, how schema linking works, what database context to supply, how to repair failing queries safely, how agents differ across SQL, NoSQL and vector stores, and what read-only really requires.
Prerequisites: Data Agents and AI Data Analysts and basic SQL.
The example runs in November 2026 with Python 3.13 and only the standard library. The schema, synonyms and join keys are invented. Research and product facts were checked on November 28, 2026.
SQL agent architecture
A single model call that receives a schema and a question can work for a database with a handful of tables. Real warehouses have hundreds or thousands, with similar names, historical leftovers and business rules that appear nowhere in the structure. An agent splits the work into steps that can each be checked.
| Component | Job | Mostly done by |
|---|---|---|
| Question analysis | Identify measures, filters, grouping and period | Model |
| Schema linker | Select tables, columns and values | Search, rules and model |
| Context builder | Assemble definitions, joins and examples | Code |
| Generator | Write SQL in the right dialect | Model |
| Validator | Parse, check permissions and cost | Code and database |
| Executor | Run with timeouts and row limits | Database |
| Checker | Look for empty, duplicated or implausible results | Code, then model |
| Explainer | Describe the answer and assumptions | Model |
Schema linking in plain words
Suppose someone asks for "sales by region and product category". The database has no column called sales. It has net_amount on order lines. Region names live in a lookup table connected through customers. Category is on products. Schema linking has to discover all of this: map "sales" to a column, find two dimension tables, and add the customer table that nobody mentioned because it is the only way to join them.
It can go wrong in recognizable ways:
- Missing table. A join path needs an intermediate table that the question never names.
- Lookalike table. A staging, archive or test copy is chosen instead of the maintained one.
- Wrong column.
created_atis used when the business means ship date. - Value mismatch. The question says "Germany" and the column stores
DE. - Grain error. Joining order headers to lines and then summing a header amount counts it several times.
Database context the model needs
A schema dump is a poor brief. It is large and says little about meaning. Supply compact, relevant information instead.
| Context item | Helps with | Caution |
|---|---|---|
| Table purpose and grain | Choosing the right table | Keep it to a sentence or two |
| Column descriptions and units | Choosing columns and arithmetic | Stale descriptions mislead |
| Primary and foreign keys | Join paths | Declare logical keys the database does not enforce |
| Allowed values for categories | Correct filter literals | Never include personal or secret values |
| Metric definitions | Business logic | Prefer certified ones |
| Verified example queries | House style and tricky joins | Retest them when schemas change |
| Dialect and version | Valid functions and date handling | State it explicitly |
| Deprecations and warnings | Avoiding traps | Remove dead tables from the index |
Sample rows are tempting because they show formats. They can also expose personal data to the model and logs. Prefer synthetic examples or reviewed lists of non-sensitive category values, following PII Redaction and Data Leakage Prevention.
Methods that combine well
| Method | How it works | Good at |
|---|---|---|
| Keyword and synonym match | Words against names, descriptions and a glossary | Known business terms |
| Semantic search | Embeddings over table and column descriptions | Paraphrases |
| Value index | Search distinct category values | Names, codes and places |
| Join graph | Path search across declared relationships | Intermediate tables |
| Usage signals | Rank tables that reviewed queries actually use | Avoiding abandoned copies |
| Model selection | Model picks from a shortlist and gives reasons | Final disambiguation |
Filter by permission first. The shortlist should contain only objects the asking person may use, so that restricted names do not leak into prompts or answers. Then favor recall: a few extra tables cost some tokens, while a missing table usually makes a correct query impossible. Embeddings, Vector and Hybrid Search, Reranking describes the search techniques.
Linking a question to a small schema
The program matches question words to columns through a synonym table, matches table names, then walks the foreign key graph to connect what it found. It reports why each table was chosen, which is worth logging in a real system.
"""Schema linking: pick the tables a question needs, then add join paths."""
import re
from collections import deque
TABLES = {
"customers": {"about": "one row per customer account",
"columns": ["customer_id", "name", "region_id", "segment"]},
"regions": {"about": "sales region lookup",
"columns": ["region_id", "region_name"]},
"orders": {"about": "one row per order header",
"columns": ["order_id", "customer_id", "order_date", "status"]},
"order_lines": {"about": "one row per product on an order",
"columns": ["order_id", "product_id", "quantity", "net_amount"]},
"products": {"about": "product catalog",
"columns": ["product_id", "product_name", "category"]},
"tickets": {"about": "support tickets raised by customers",
"columns": ["ticket_id", "customer_id", "opened_at", "priority"]},
"employees": {"about": "staff directory",
"columns": ["employee_id", "name", "team", "salary_band"]},
"web_events": {"about": "raw clickstream from the website",
"columns": ["event_id", "session_id", "url", "ts"]},
}
SYNONYMS = {"sales": "net_amount", "revenue": "net_amount",
"territory": "region_name", "region": "region_name",
"category": "category", "month": "order_date"}
JOINS = [("customers", "regions", "region_id"),
("orders", "customers", "customer_id"),
("order_lines", "orders", "order_id"),
("order_lines", "products", "product_id"),
("tickets", "customers", "customer_id")]
def words(text):
return {w.rstrip("s") for w in re.findall(r"[a-z]+", text.lower())}
def link(question):
asked = words(question)
wanted = {SYNONYMS[w] for w in SYNONYMS if w.rstrip("s") in asked}
hits = {}
for table, info in TABLES.items():
reasons = [c for c in info["columns"] if c in wanted]
if table.rstrip("s") in asked:
reasons.append("table name")
if reasons:
hits[table] = reasons
return hits
def path(start, goal):
queue = deque([[start]])
seen = {start}
while queue:
route = queue.popleft()
if route[-1] == goal:
return route
for a, b, _ in JOINS:
for here, there in ((a, b), (b, a)):
if here == route[-1] and there not in seen:
seen.add(there)
queue.append(route + [there])
return []
def connect(tables):
chosen = [tables[0]]
for table in tables[1:]:
best = min((path(c, table) for c in chosen), key=len)
chosen += [t for t in best if t not in chosen]
return chosen
def size(tables):
return sum(len(TABLES[t]["about"]) + len(" ".join(TABLES[t]["columns"]))
for t in tables)
question = "Show sales by region and product category for each month"
hits = link(question)
print("Question:", question)
for table, reasons in hits.items():
print(f" matched {table:<12} because of {', '.join(reasons)}")
chosen = connect(list(hits))
print("Added for joins:", ", ".join(t for t in chosen if t not in hits) or "none")
print("Context tables:", ", ".join(chosen))
for a, b, key in JOINS:
if a in chosen and b in chosen:
print(f" join {a}.{key} = {b}.{key}")
print(f"Schema text: {size(chosen)} characters, full schema {size(TABLES)}")
print("Left out:", ", ".join(t for t in TABLES if t not in chosen))
Output:
Question: Show sales by region and product category for each month
matched regions because of region_name, table name
matched orders because of order_date
matched order_lines because of net_amount
matched products because of category, table name
Added for joins: customers
Context tables: regions, customers, orders, order_lines, products
join customers.region_id = regions.region_id
join orders.customer_id = customers.customer_id
join order_lines.order_id = orders.order_id
join order_lines.product_id = products.product_id
Schema text: 281 characters, full schema 462
Left out: tickets, employees, web_events
The customers table appears only because the join search needed it. The employee, ticket and clickstream tables never reach the model, which shrinks the prompt and removes chances to make mistakes with them, including a table that holds salary bands. The method is deliberately crude: "month" matched order_date because someone wrote that synonym, and a question using an unlisted word would find nothing. Real linkers add the search methods above and ask the person when coverage is weak. The path search also takes a shortest route, which is not always the meaningful one. When two routes exist, such as billing region and shipping region, the choice is a business rule that should be written down.
Generating the query
Give the generator the shortlist, join conditions, definitions, dialect and a few similar verified queries. Ask for structured output containing the query, the assumptions and the tables used, as in Message Roles, Structured Output and Function Calling. Useful instructions include:
- Select named columns, never everything.
- Aggregate at the correct grain before joining one-to-many relations.
- Use half-open date ranges, from the start up to but excluding the end.
- Handle nulls and division by zero deliberately.
- Return a clarification request when required information is missing.
- Use bound parameters for values taken from user text where the executor supports them.
Some teams generate several candidates and compare their results. Agreement raises confidence a little and disagreement is a good reason to ask, but candidates from one model tend to share the same misunderstanding, so agreement proves nothing about meaning.
Validate and repair
Before execution, parse the query with a real SQL parser for your dialect, confirm it is a single read statement, check referenced objects against the allowed set and ask the database for a plan or a dry run where it offers one. Errors give precise feedback that models use well. Set limits on the loop.
| Signal | Action |
|---|---|
| Syntax or unknown column | Return the error and retry, with a small cap |
| Permission denied | Stop and explain; never search for a way around it |
| Timeout or cost limit | Ask to narrow the period or scope |
| Empty result | Check filter values and period before reporting zero |
| Row count far above expectation | Check joins for duplication |
| Same failure twice | Stop and hand over with the attempts attached |
A repair loop has a subtle risk. An agent rewarded for producing any result may remove a filter or join until the error disappears. Compare the repaired query with the original interpretation and reject changes in meaning.
Verified queries
A library of reviewed question and query pairs is among the most practical assets a SQL agent can have. Retrieve the closest examples for each new question, and run a matching verified query directly with new parameters when the fit is exact. Store the owner, the review date and the schema version. Snowflake's August 2026 transition note from Cortex Analyst to Cortex Agents is a reminder to check which of these assets move with you when a product changes. Keep a copy in your own version control.
Follow-ups and conversation
When someone says "now just for enterprise customers", change the structured interpretation and regenerate or edit the query. Show what changed. Do not let the previous result stand in for a new query, and rerun checks because a new filter can produce a tiny sample or an empty set.
Large and messy schemas
Public benchmarks show how much harder realistic work is than classroom queries. Spider 2.0, presented at ICLR 2025, contains 632 problems drawn from enterprise data workflows, involving large schemas, multiple SQL dialects and project code. Use benchmarks to compare approaches roughly, and read Safe SQL, Permissions and Evaluation for their limits. For your own large estate:
- Route each question to a domain first, then link within that domain.
- Publish curated views for agents so that they never see the raw sprawl.
- Index descriptions and refresh the index when schemas change.
- Let the agent explore the catalog with tools instead of pasting everything into context.
- Record which objects were retrieved but unused, and which were needed but missed.
SQL, NoSQL and vector databases
The same loop applies to other stores, but each has its own way to go wrong.
| Store | Context needed | Particular risk |
|---|---|---|
| Relational and warehouse | Keys, grain, dialect, definitions | Duplicating joins, expensive scans |
| Document store | Inferred shape, optional fields, indexes | Fields that exist only in some documents |
| Key-value store | Key patterns and access paths | Scanning everything to find one item |
| Graph database | Node and relationship types | Unbounded traversals |
| Time series | Sampling interval, units, retention | Aggregating counters as if they were gauges |
| Search and vector index | Fields, filters, embedding model | Treating nearest matches as exact facts |
Vector search finds similar items. It does not count, total or prove absence. If someone asks how many contracts mention a clause, similarity search over the top results cannot answer; a structured extraction or full-text query can. For graphs, see Building and Governing Knowledge Graphs. For agents spanning several stores, give each its own narrow tool, join results in code and report which store each figure came from.
Prefer typed tools such as "orders by customer and date range" for frequent operations. Free-form query tools are best kept for exploration, where flexibility matters and a person reviews the outcome. Designing Tool Schemas and Contracts covers how to shape them.
Read-only access, properly
A prompt saying "only read data" is a request. Access control is what the database will refuse to do. Build several layers.
- Grant read rights on specific views, and no rights to create, change or execute powerful functions.
- Remember that a statement beginning with
SELECTcan call functions with side effects in some databases. - Point exploratory work at a replica or separate compute so it cannot slow operations.
- Do not reuse an application account that also writes.
- Test the role by trying forbidden statements automatically on every release.
Writes, when a use case needs them, should go through narrow, approved operations with their own checks rather than generated SQL. See Reliable Tool Execution and Error Recovery.
Untrusted text inside data
Query results can contain instructions written by outsiders: a product review, a support message or a name field. Treat returned rows as data. Do not let them change which tools run next, and escape them when rendering charts or links. Prompt Injection Attacks and Defenses explains why filtering text is not enough and permissions must limit the damage.
Operating practices
- Log question, retrieved objects, query, plan estimate, duration and outcome, with sensitive values masked.
- Cache schema and definition lookups, and invalidate them on change.
- Review failed and corrected questions weekly and turn each into a test.
- Assign owners to domains so that fixes have somewhere to go.
- Pin model and prompt versions, and compare before upgrading.
- Tell users when a result is exploratory.
Common mistakes
| Mistake | Consequence | Instead |
|---|---|---|
| Pasting the whole schema | Cost, noise and wrong tables | Link and shortlist |
| Descriptions nobody maintains | Confidently outdated queries | Owners and change checks |
| Unlimited repair attempts | Meaning drifts until something runs | Cap retries and compare intent |
| Real sample rows in prompts | Personal data spreads to logs | Synthetic or reviewed values |
| Read-only by instruction | One clever input writes data | Database grants and read sessions |
| Reporting empty as zero | False conclusions | Check filters, period and permissions |
Checklist
- Schema retrieval is filtered by the user's permissions.
- Tables have purpose, grain and join keys recorded.
- Verified queries are versioned and retested.
- Generated SQL is parsed and limited to one read statement.
- Database roles refuse writes independently of the agent.
- Timeouts, row limits and cost limits apply to every query.
- Retries are capped and permission errors stop the run.
- Linking failures are logged and reviewed.
Frequently asked questions
Is a bigger context window a substitute for schema linking?
It lets you include more, but irrelevant and lookalike objects still invite mistakes and cost money, so selection remains worthwhile.
Should we fine-tune a model for our dialect?
Start with good descriptions, verified examples and validation. Consider fine-tuning only if a measured gap remains and you can maintain the training data.
Can the agent create temporary tables?
That is a write permission. If analysis needs it, use an isolated scratch area with quotas and expiry, separate from governed data.
How many retries are reasonable?
A very small number, set from your own measurements. Repeated failure usually means missing context that another attempt will not supply.
References
- Spider 2.0 benchmark site
- Spider 2.0 paper on arXiv
- PostgreSQL: row security policies
- SQLite: compile-time authorization callbacks
- Snowflake: transition from Cortex Analyst to Cortex Agents
Where to go next
Safe SQL, Permissions and Evaluation
Enforce limits and measure accuracy.
Semantic Layers and Business Metrics for AI
Move business logic out of prompts.
Data Engineering, Catalog and Quality Agents
Keep the underlying data trustworthy.