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.

BeginnerIntermediateExpert · 14 min read · Last updated:

In short

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.

Versions used

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.

Beginner How a SQL agent works

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.

Linkschema
Draftquery
Validatepolicy
Runlimited
Verifyresult
A failure at validate or verify returns to an earlier step, within a retry budget.
ComponentJobMostly done by
Question analysisIdentify measures, filters, grouping and periodModel
Schema linkerSelect tables, columns and valuesSearch, rules and model
Context builderAssemble definitions, joins and examplesCode
GeneratorWrite SQL in the right dialectModel
ValidatorParse, check permissions and costCode and database
ExecutorRun with timeouts and row limitsDatabase
CheckerLook for empty, duplicated or implausible resultsCode, then model
ExplainerDescribe the answer and assumptionsModel

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_at is 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 itemHelps withCaution
Table purpose and grainChoosing the right tableKeep it to a sentence or two
Column descriptions and unitsChoosing columns and arithmeticStale descriptions mislead
Primary and foreign keysJoin pathsDeclare logical keys the database does not enforce
Allowed values for categoriesCorrect filter literalsNever include personal or secret values
Metric definitionsBusiness logicPrefer certified ones
Verified example queriesHouse style and tricky joinsRetest them when schemas change
Dialect and versionValid functions and date handlingState it explicitly
Deprecations and warningsAvoiding trapsRemove 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.

Intermediate Linking methods, example and repair

Methods that combine well

MethodHow it worksGood at
Keyword and synonym matchWords against names, descriptions and a glossaryKnown business terms
Semantic searchEmbeddings over table and column descriptionsParaphrases
Value indexSearch distinct category valuesNames, codes and places
Join graphPath search across declared relationshipsIntermediate tables
Usage signalsRank tables that reviewed queries actually useAvoiding abandoned copies
Model selectionModel picks from a shortlist and gives reasonsFinal 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.

SignalAction
Syntax or unknown columnReturn the error and retry, with a small cap
Permission deniedStop and explain; never search for a way around it
Timeout or cost limitAsk to narrow the period or scope
Empty resultCheck filter values and period before reporting zero
Row count far above expectationCheck joins for duplication
Same failure twiceStop 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.

Expert Scale, database types and access

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.

StoreContext neededParticular risk
Relational and warehouseKeys, grain, dialect, definitionsDuplicating joins, expensive scans
Document storeInferred shape, optional fields, indexesFields that exist only in some documents
Key-value storeKey patterns and access pathsScanning everything to find one item
Graph databaseNode and relationship typesUnbounded traversals
Time seriesSampling interval, units, retentionAggregating counters as if they were gauges
Search and vector indexFields, filters, embedding modelTreating 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.

Identityuser's own or a narrow read role
Objectscurated views; row and column rules
Sessionread-only transaction, statement timeout
Gatewayone parsed statement, row and cost limits
Any single layer can have a gap, so none of them stands alone.
  • Grant read rights on specific views, and no rights to create, change or execute powerful functions.
  • Remember that a statement beginning with SELECT can 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

MistakeConsequenceInstead
Pasting the whole schemaCost, noise and wrong tablesLink and shortlist
Descriptions nobody maintainsConfidently outdated queriesOwners and change checks
Unlimited repair attemptsMeaning drifts until something runsCap retries and compare intent
Real sample rows in promptsPersonal data spreads to logsSynthetic or reviewed values
Read-only by instructionOne clever input writes dataDatabase grants and read sessions
Reporting empty as zeroFalse conclusionsCheck 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

Where to go next