🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Text-to-SQL: Schema Linking and Safe Query Generation

đŸŸĸ Free Lesson

Text-to-SQL

Prerequisites

  • !SQL joins, aggregation and CTEs
  • !How relational schemas describe business entities
  • !Model evaluation with programmatic checks

What You'll Learn

  • 1Explain why large schemas defeat naive prompting and how linking fixes it
  • 2Select relevant tables and columns before generation
  • 3Write execution guards that make generated SQL safe by construction
  • 4Evaluate with execution accuracy and repair failures with an error loop

Real warehouses do not look like tutorial databases

A textbook example has three tables and one obvious join path. A production warehouse has hundreds of tables, forty of which contain something that could be called revenue, plus fifteen reporting views layered over them by analysts who left the company. Ask a model for "monthly revenue by region" against that schema and it will produce syntactically perfect SQL against the wrong table — fct_revenue_daily instead of mart_revenue_booked — with a confidence that no error message will challenge, because the query runs.

The failure is informational, not linguistic. The model cannot see which of the forty candidates your organisation considers canonical, which columns are populated, or that "revenue" excludes refunds in one table and includes them in another. Three interventions address this in order: give the model only the relevant schema fragments, describe the semantics and conventions alongside them, and validate the result against the database before anyone sees it.

StageInputOutputTypical failure
Question parsingUser utteranceIntent, metrics, dimensionsAmbiguous business terms
Schema linkingFull catalog, utteranceRelevant tables and columnsMissed lookup table
GenerationQuestion + linked schemaSQL textWrong grain, wrong dialect
ValidationSQL textAllowed or blockedGuards too permissive
ExecutionSQL on warehouseRows or errorTimeout, fan-out
RepairError messageRevised SQLInfinite retry loops

Schema linking deserves the most attention: it is cheap, it removes the majority of errors, and it reduces prompt size enough that the model can afford to include sample values and business definitions for the tables that matter.

Selecting the schema the model should see

Retrieval over the catalog works the way retrieval works anywhere else: score table and column descriptions against the question, keep a budget of the best candidates, and always include the tables that the chosen ones reference as foreign keys.

python
import re
from collections import Counter


def link_schema(question: str, catalog: dict, max_tables: int = 6) -> dict:
    """catalog: {table: {"description": str, "columns": {col: desc}, "refs": [fk]}}"""
    q_terms = set(re.findall(r"[a-z0-9']+", question.lower()))
    scored = []

    for table, meta in catalog.items():
        hay = " ".join([
            table.lower().replace("_", " "),
            meta.get("description", ""),
            " ".join(f"{c.lower()} {d}" for c, d in meta["columns"].items()),
        ])
        hay_terms = set(re.findall(r"[a-z0-9']+", hay))
        overlap = len(q_terms & hay_terms)
        coverage = overlap / max(1, len(q_terms))
        exact = 2.0 if table.lower().replace("_", " ") in question.lower() else 0.0
        scored.append((table, coverage + exact))

    scored.sort(key=lambda s: -s[1])
    chosen = [t for t, s in scored[:max_tables] if s > 0.15] or [scored[0][0]]

    # Pull in referenced tables so joins do not have to be invented.
    for table in list(chosen):
        for ref in catalog.get(table, {}).get("refs", []):
            if ref not in chosen:
                chosen.append(ref)

    return {
        "tables": {t: catalog[t] for t in chosen if t in catalog},
        "scores": dict(scored[:max_tables]),
    }


CATALOG = {
    "fct_orders": {
        "description": "One row per captured order; excludes test accounts",
        "columns": {"order_id": "primary key", "booked_at": "timestamp UTC",
                    "amount_usd": "net of discounts, before refunds",
                    "region_id": "foreign key to dim_region"},
        "refs": ["dim_region"],
    },
    "dim_region": {
        "description": "Sales regions as defined by the current fiscal year",
        "columns": {"region_id": "primary key", "region_name": "label"},
        "refs": [],
    },
    "fct_revenue_daily": {
        "description": "Finance ledger snapshot including refunds",
        "columns": {"day": "date", "booked_revenue": "ledger amount"},
        "refs": [],
    },
}

print(link_schema("monthly revenue by region", CATALOG)["tables"].keys())
# -> fct_orders, dim_region (finance ledger table scores lower)

Two rules keep linking honest. Foreign-key expansion is mandatory — a model that retrieves the fact table but not its dimension will fabricate a join key. And a score floor with a fallback (take the top candidate anyway) handles questions whose vocabulary matches nothing, which usually means the business term needs a synonym entry rather than a better ranker.

Teaching the dialect and the house conventions

With the right tables in hand, the prompt should carry the knowledge that lives in your team's heads: which engine, which date functions, which grain is canonical, and which columns to avoid.

-- Catalog excerpt: rendered into the prompt, not the model's memory.
CREATE TABLE fct_orders (
    order_id     BIGINT PRIMARY KEY,
    booked_at    TIMESTAMP NOT NULL,        -- always UTC
    amount_usd   NUMERIC(12, 2),            -- net of discounts, pre-refund
    region_id    INT REFERENCES dim_region (region_id),
    account_id   BIGINT NOT NULL,
    status       TEXT CHECK (status IN ('captured', 'void', 'test'))
);

-- Conventions
-- Engine: Snowflake. Dates: DATE_TRUNC('month', booked_at), not strftime.
-- Filter status = 'captured'; test rows use status = 'test' and must be excluded.
-- Grain: one row per order. Never sum amount_usd across a join to line items
--        without DISTINCT order_id first.
-- Prefer mart_* views for reporting questions when they exist.
-- Amounts are USD cents divided by 100 in legacy tables; this table is dollars.

That excerpt prevents four separate classes of bug: timezone errors, unfiltered test rows, double counting through fan-out joins, and unit mismatches between legacy and current tables. None of them would be caught by a syntax check, and all of them produce plausible numbers.

Execution guards: safe by construction

Never run model output directly. A guard layer should reject anything that is not a read, bound the work it can do, and verify the result shape before returning rows.

python
import re
import sqlparse


FORBIDDEN = re.compile(
    r"\b(DROP|DELETE|TRUNCATE|ALTER|UPDATE|INSERT|MERGE|GRANT|CREATE|"
    r"CALL|EXECUTE|COPY)\b",
    re.IGNORECASE,
)


def guard_sql(sql: str, max_rows: int = 5000, timeout_s: int = 20) -> dict:
    statements = [s for s in sqlparse.parse(sql) if str(s).strip()]
    if len(statements) != 1:
        return {"ok": False, "reason": "expected exactly one statement"}

    stmt = statements[0]
    if stmt.get_type() != "SELECT":
        return {"ok": False, "reason": "only SELECT statements are allowed"}
    if FORBIDDEN.search(str(stmt)):
        return {"ok": False, "reason": "forbidden keyword present"}

    text = str(stmt).rstrip().rstrip(";").strip()
    if not text:
        return {"ok": False, "reason": "empty statement"}

    return {
        "ok": True,
        "sql": f"SELECT * FROM ({text}) LIMIT {max_rows}",
        "timeout_s": timeout_s,
        "comment": "-- guarded: read-only, row-bounded, warehouse-level timeout",
    }


print(guard_sql("SELECT region_id, SUM(amount_usd) FROM fct_orders GROUP BY 1"))
print(guard_sql("DROP TABLE fct_orders"))

Wrap the query in an outer limit rather than trusting the model to add LIMIT — a cartesian join without one will saturate the warehouse before anyone notices. Set the timeout at the connection level as well as the application level, and run the guarded query against a read-only role so a bug in the guard is contained rather than catastrophic.

âš ī¸Guard against the semicolon too

A single-statement policy must reject SELECT 1; DROP TABLE users — some drivers execute only the first statement, others concatenate them. Parsing the full string and requiring exactly one statement removes the ambiguity entirely.

A metric dictionary beats a smarter model

Ambiguity at the business level is not resolved by generation quality. "Active customer", "revenue", "churn rate" and "this quarter" each have a documented definition somewhere — in a metrics layer, a dbt model, a wiki page nobody updated — and the model will choose the most common usage from its pretraining unless you supply yours.

Give every frequently asked metric an entry with its name, the canonical SQL fragment, the grain it assumes, and the filters it requires. At question time, resolve the metric first, then generate the query around the resolved fragment rather than letting the model re-derive the formula. This converts an open-ended generation problem into a constrained one: the model's remaining work is selecting dimensions, grouping and ordering — the parts where it is reliably strong — while the definition, where it is reliably overconfident, comes from your own records.

The dictionary also becomes the audit trail product and finance teams ask for. When someone challenges a number in a dashboard, the answer is a link to the metric entry and the generated query, not a conversation about what the model might have meant. Metrics that nobody can locate in the dictionary are exactly the ones worth adding first, because those are the questions the system currently answers by guessing.

Evaluating execution, not string equality

Two queries that differ by whitespace, alias names or CTE ordering are identical in effect; two queries with identical text against different schemas are not. Execution accuracy — does the query run, and do its results match a reference result set — is the metric that corresponds to users.

MetricMeasuresMisses
Exact string matchSurface fidelityEquivalent rewrites
Executable rateSyntax and schema validityWrong answer, right syntax
Execution accuracyResult equality with referenceRows that agree by coincidence
Partial execution accuracyOverlapping result rowsOrder-dependent outputs
LatencyWarehouse cost of the answerAnswer quality

Report all of the middle three. Executable rate diagnoses grammar and dialect problems; execution accuracy diagnoses semantics; the gap between them is the size of your "runs but lies" problem. Beware result-set coincidence: on small reference sets, a query with a subtly wrong join can still match, so include cardinality checks and at least one large reference case per template.

Repair loops and the ambiguity users actually mean

When execution fails, feed the error back with the original question and the schema excerpt and ask for one revision, bounded to two or three attempts; beyond that, retry loops burn seconds and produce increasingly creative SQL. Most repairable errors cluster into four types — unknown column, wrong function for the dialect, missing join path, and type mismatch — and the fix for each is usually to add the missing schema detail rather than to argue with the model.

When execution succeeds but the answer looks wrong, sample ten rows and show them to the user as a preview with the query attached. Transparency does double duty: it lets a domain expert spot a wrong grain instantly, and it teaches users the vocabulary the system understands. Finally, embrace clarification for genuinely ambiguous questions. "Revenue by region" means booked or recognised? Fiscal or calendar months? A system that asks one follow-up question answers correctly on the first try; a system that guesses silently answers wrong with confidence, and confidence is what users act on.

Common Mistakes

Sending the entire catalog to the model

Fix: Link the relevant tables first, expand foreign keys, and include only those DDL fragments

Running generated SQL without a guard layer

Fix: Parse for a single SELECT, forbid destructive keywords, wrap in a row limit and use a read-only role

Scoring with exact string match alone

Fix: Measure executable rate and execution accuracy, and keep large reference cases to avoid coincidental matches

Retrying failures without adding information

Fix: Return the error plus the missing schema detail, and cap attempts before escalating

Best Practices

  • Put house conventions — date functions, status filters, canonical views — in the prompt excerpt
  • Expand foreign keys during linking so joins are retrieved, not invented
  • Bound every query with a warehouse-side timeout and an outer row limit
  • Preview sample rows alongside answers so domain experts can catch wrong grain immediately
  • Log linked schemas and generated SQL together; they are the debugging record for every bad answer

Key Takeaways

  • Text-to-SQL fails on schema ambiguity far more often than on grammar
  • Linking plus foreign-key expansion shrinks the prompt and removes most wrong-table errors
  • House conventions and dialect notes in the prompt prevent bugs no syntax check can catch
  • Guards must enforce a single read-only statement with a row bound and a timeout
  • Evaluate with execution accuracy alongside executable rate, and repair failures with bounded, information-rich retries
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Generative AI Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement