RAG & retrieval Guide 23 of 25

Text-to-SQL in production: why the hard part isn’t the SQL

Today’s models write fluent SQL. Production systems still stumble on finding the right table, knowing what a column means, and catching a confident wrong number. Here is how teams that shipped handle each.

  • 9 min read
  • Updated 
  • 8 sources

Key takeaways

  • Writing SQL is now the easy step. Accuracy depends on finding the right tables, knowing what columns and values mean, and supplying business definitions the model cannot guess.
  • Public benchmark scores do not transfer to your warehouse. A 2026 audit found annotation errors in over half of the BIRD Mini-Dev and Spider 2.0-Snow problems it checked.
  • Check before anyone trusts a query: confirm tables and columns exist, run EXPLAIN or a dry run, flag empty results, and feed errors back for a retry.
  • Route KPI and board-level questions through a semantic layer that refuses when unsure. Keep free-form text-to-SQL for exploration, with the SQL and assumptions shown.
  • Run generated SQL read-only, with the asking user’s own permissions and with time and cost limits. The assistant should never see more data than the person.
On this page 8 sections

Most companies with a data warehouse share the same queue: many people who need a number, and a few who know which table holds it. Uber put a size on that queue in 2024. Its data platform handled about 1.2 million interactive queries a month, and Uber estimated that each took about 10 minutes to write. Text-to-SQL, where a large language model (LLM) turns a plain-English question into Structured Query Language (SQL), promises to shrink that wait to a chat message.

The promise is half kept. Google’s text-to-SQL team noted in May 2025 that current models already turn complex questions into working SQL with joins, filters, and aggregations. What still breaks is everything around the query. Systems must pick the right table out of thousands, know that “active” means something specific at your company, and notice when a query runs cleanly but returns the wrong number.

This guide covers how production systems handle those problems, as of October 2026. It draws on engineering write-ups from Uber, Pinterest, LinkedIn, Google Cloud, and OpenAI, plus recent research on why benchmark scores mislead.

What does a text-to-SQL system actually have to do?

A demo takes a question and a schema and returns a query. A production system has more jobs, and generating SQL is only one of them:

  1. Interpret the question. Resolve vague terms, or ask the user what they meant.
  2. Find the data. Choose the right tables among thousands, many of them near-duplicates.
  3. Ground the details. Pick columns, join keys, and the filter values actually stored.
  4. Apply business definitions. Know how revenue, churn, or an active user is computed here.
  5. Write the SQL in the correct dialect.
  6. Check it before anyone relies on it.
  7. Run it safely, with the asking user’s permissions and sensible limits.
  8. Explain the result, including every assumption made along the way.

In the write-ups below, most of the engineering effort goes into steps 2–4 and 6, not step 5. Uber found that LLMs did best when handed one narrow job at a time, so QueryGPT splits the work across small agents. One maps the question to a business domain, one proposes tables for the user to confirm, and one trims irrelevant columns before generation.

Why don’t benchmark scores predict your accuracy?

Public benchmarks have climbed fast, which makes it tempting to read a leaderboard and assume the problem is solved. Three caveats apply first.

Classic benchmarks are easier than real warehouses. Spider 2.0, released in November 2024, uses enterprise databases that often exceed 1,000 columns. On it, an agent built on OpenAI’s o1-preview solved 21.3% of tasks, while GPT-4-based methods had already reached 91.2% on the original Spider and 73.0% on BIRD, another widely used benchmark. Pinterest saw the same gap from the other side: its system roughly matched published Spider results, yet a handful of pre-chosen tables with clearly labeled columns was far easier than its users’ real work.

The answer keys are noisy. A University of Illinois team audited both benchmarks for the Conference on Innovative Data Systems Research (CIDR) in January 2026. They found annotation errors in 52.8% of BIRD’s Mini-Dev problems and 66.1% of the Spider 2.0-Snow problems they could check. After corrections, one agent’s accuracy on a 100-question BIRD sample rose from 62% to 81%, lifting it from fourth to first of the five agents tested.

Vendors hedge too. Google’s team treats BIRD as a useful baseline but adds internal benchmarks covering more dialects, schemas, and workloads. The practical conclusion: a few leaderboard points tell you little, while an evaluation set built from your own questions tells you a lot.

Is finding the right table the real problem?

For most enterprises, yes. Pinterest’s first version assumed users knew which tables to use, but identifying them among hundreds of thousands was the harder task. LinkedIn’s warehouse holds millions of tables. OpenAI’s internal platform, as of its January 2026 write-up, spans more than 600 petabytes across 70,000 datasets, and one user described spending a lot of time telling near-identical tables apart.

The common answer is retrieval-augmented generation (RAG) over metadata rather than over raw data. Pinterest has an LLM summarize each table from its schema and sample queries, embeds those summaries, and searches them for each question. A second LLM call narrows the candidates, and the user confirms the final list. LinkedIn trims its pool by access popularity and uses the org chart to set each user’s default datasets, then retrieves 20 candidate tables and has an LLM reranker keep 7.

The lever underneath is documentation. In Pinterest’s tests, table search scored a 40% hit rate when the embeddings left out table documentation, climbing steadily to 90% as documentation carried more weight. Pinterest also indexed only its top-tier tables, steering the model toward vetted data. Text-to-SQL, in other words, is largely a data-governance project with a chat box on top.

Values and definitions matter as much as names

Knowing the column is not enough; the model must know what is stored in it. Pinterest adds the distinct values of low-cardinality columns to the schema, so a filter uses the stored spelling rather than a guess. Uber tracks whether each query returns any rows at all, because an invented status value runs without error and simply returns nothing.

Business meaning is harder still. OpenAI’s agent draws on six layers of context: table usage, expert annotations, internal documents, saved corrections, live queries, and code-level enrichment. That last layer uses Codex, OpenAI’s coding agent, to read the pipeline code that builds each table. OpenAI’s stated lesson is that what a table really means sits in that code, not in the schema or query history.

How do production systems check the SQL?

LLM output varies from run to run, so serious systems add deterministic checks. Google’s team parses queries or dry-runs them, then hands any error back to the model for another attempt. It also generates several candidate queries, sometimes with different prompts or models, and keeps the strongest. LinkedIn confirms that tables and fields exist and runs EXPLAIN, then a self-correction agent repairs what failed.

Checks should cover the result as well as the syntax. OpenAI’s agent reviews intermediate results and changes course when one looks wrong, such as zero rows after a bad join. A minimal loop looks like this:

def answer(question, user):
    # Ask, or state the default used.
    question = clarify_or_default(question)
    # Metadata RAG, then an LLM reranker.
    tables = rerank(retrieve_tables(question), question)
    context = build_context(
        tables, sample_values=True, metric_definitions=True)
    for attempt in range(3):
        sql = generate_sql(question, context)
        # Parses, names exist, one SELECT only; then
        # EXPLAIN or a dry run with the user's permissions.
        problems = (
            static_checks(sql, tables)
            or dry_run(sql, as_user=user)
        )
        if not problems:
            rows = execute(
                sql, as_user=user,
                timeout_s=60, max_scan_gb=50)
            # Empty, mostly nulls, implausible totals.
            problems = sanity_checks(rows)
            if not problems:
                notes = list_assumptions(question, tables)
                return rows, sql, notes
        context = add_feedback(context, problems)
    return hand_off_to_analyst(question, sql, problems)

Ambiguity needs its own handling: “top customers last quarter” could mean ranked by revenue or by order count, over a calendar or a fiscal quarter. Google’s system first asks whether a question is answerable with the available data, and generates a clarifying question if not. OpenAI’s agent also asks, but applies a sensible default, such as the last 7 or 30 days, when nobody replies. Either way, show the assumption next to the number.

Should you use a semantic layer instead?

A semantic layer defines metrics, dimensions, and join paths once, in code. The model only picks a metric and its dimensions, and a deterministic engine writes the SQL. dbt Labs, which sells such a layer, reran its comparison in April 2026 on an insurance dataset, running 11 questions 20 times each.

The results cut both ways. On the original schema, raw text-to-SQL accuracy roughly doubled from the 2023 GPT-4 run, rising from 32.7% to 64.5%. After an LLM added three pre-joined dbt models, which both approaches could use, the semantic layer scored 98.2% with Claude Sonnet 4.6 and 100% with GPT-5.3 Codex, against 90.0% and 84.1% for text-to-SQL.

Read those figures with care. The benchmark is small, the publisher has a product in the race, and the text-to-SQL runs received the entire schema in context, which large warehouses cannot afford.

The bigger finding is how each approach fails: the semantic layer says it cannot answer, while text-to-SQL “will cheerfully give you a wrong number.” That difference holds whatever the caveats, and it should drive the design.

AspectRaw text-to-SQLSemantic layerHybrid
CoverageAny question the data can answerOnly modeled metrics and dimensionsModeled questions first, raw SQL as fallback
Typical failurePlausible but wrong numberExplicit refusalRefusal, then a clearly labeled exploratory answer
Up-front costMetadata, sample values, example queriesModeling every metric you care aboutBoth, built incrementally
Best forAnalysts exploring and drafting queriesKey performance indicators (KPIs), finance, board reportingSelf-serve for mixed audiences

Who should be allowed to run what?

A text-to-SQL system executes code a model wrote from text a user typed, so treat it like untrusted code. OpenAI’s agent uses pass-through access: users can query only tables they could already reach, and the agent points to permitted alternatives when access is missing. At LinkedIn, each dataset carries a separate access control list. When a user belongs to a group that can read the table, SQL Bot supplies the code to use that group’s credentials, rather than granting anything new.

The remaining defaults are ordinary database hygiene. Use a read-only role, reject anything except a single SELECT statement at parse time, and set statement timeouts and scan limits so one question cannot run up a large bill. The read-only role is the real guard, since a parser check can miss side-effecting functions or dialect quirks. Remember that table comments and column values flow into the prompt, so they can carry injected instructions like any other untrusted text.

How do you know if it is working?

Start with a golden set: real questions from your logs, each paired with verified SQL. Uber built its set from QueryGPT logs and scores each stage separately: domain choice, table overlap, whether the query ran, whether it returned rows, and similarity to the reference. Uber also learned to discount run-to-run swings of about 5% and to look for patterns over time instead.

Never grade by exact string match, because two correct queries can look nothing alike. OpenAI executes each generated query alongside a hand-written golden query, compares both the SQL and the returned data, and passes those signals to an automated grader.

LinkedIn chose differently: it grades with human reviewers and an LLM judge, which it found more practical than executing queries because no data access is needed. About 60% of its 130-plus benchmark questions now carry multiple accepted answers. Its LLM judge scores within one point of human reviewers 75% of the time, and experts add newly accepted answers every three months.

Usage data completes the picture. Pinterest’s first-shot acceptance rate rose from 20% to above 40%, and its uncontrolled production data showed 35% faster query writing. At Uber, 78% of users in a limited release said QueryGPT cut their query-writing time; at LinkedIn, an easy-to-build “Fix with AI” button on failed queries drives 80% of sessions. None of these is an accuracy benchmark; all are self-reported product metrics.

Before you ship a data assistant

Decide who the user is first. Analysts who read SQL gain from a drafting assistant even at 40% first-shot acceptance. Executives who cannot read SQL need governed answers, because one wrong revenue figure costs more trust than the tool earns.

Fund the metadata before the model. Pick your top-tier tables, write descriptions, record sample values, and capture metric definitions. Index only what you would vouch for. Better context is the common thread in every write-up cited here.

Build the evaluation set before the pipeline. Collect 100–300 real questions with verified answers, the range our evals guide suggests for cheap-to-label items, and score them on results. That set will tell you more than any leaderboard.

Route by stakes. Send KPI questions through a semantic layer or certified queries. Use free-form text-to-SQL for exploration, and label its answers as exploratory.

Show the work. Display the tables, SQL, and assumptions beside every answer, and make correcting them a single click.

Common pitfalls to avoid:

  • Treating “the query ran” as success.
  • Pasting the entire schema into every prompt instead of retrieving what matters.
  • Giving the assistant a service account with broader access than its users.
  • Choosing a vendor or model on public benchmark scores alone.

If you are scoping a natural-language interface to your warehouse, our analytics and data platform work starts where these teams did: with metadata, metric definitions, and evals.

Sources

  1. QueryGPT – Natural Language to SQL Using Generative AI (opens in new tab) — Uber Engineering, 2024 uber.com

  2. How we built Text-to-SQL at Pinterest (opens in new tab) — Pinterest Engineering, 2024 medium.com

  3. Practical text-to-SQL for data analytics (opens in new tab) — LinkedIn Engineering, 2024 linkedin.com

  4. Inside OpenAI’s in-house data agent (opens in new tab) — OpenAI, 2026 openai.com

  5. Getting AI to write good SQL: Text-to-SQL techniques explained (opens in new tab) — Google Cloud, 2025 cloud.google.com

  6. Spider 2.0: Evaluating Language Models on Real-World Enterprise Text-to-SQL Workflows (opens in new tab) — University of Hong Kong, Salesforce Research, Google, and others (arXiv; ICLR 2025), 2024 arxiv.org

  7. Text-to-SQL Benchmarks are Broken: An In-Depth Analysis of Annotation Errors (opens in new tab) — University of Illinois Urbana-Champaign (CIDR 2026), 2026 vldb.org

  8. Semantic Layer vs. Text-to-SQL: 2026 Benchmark Update (opens in new tab) — dbt Labs, 2026 docs.getdbt.com

Where this shows up in our work

Building this? Talk to an engineer.

If this guide maps to a system you’re planning, send a short brief. A senior engineer replies within one business day.