esc
  • WorkflowsPages
  • Case studiesPages
  • Machine Learning FoundationsLearn
  • AI EngineeringLearn
  • AI Guardrails & Red TeamingLearn
  • UI/UXLearn
  • Design SystemsLearn
  • Production System DesignLearn
  • AI papersPages
  • Interview KitPages
  • Book a callContact
  • Download ResumeContact
Let’s talk

I’ll build the agent for it.

Is Text-to-SQL Retrieval?

How text-to-SQL fetches facts from a database, how it differs from vector search, and how to keep it safe, explained for your AI interview.

In short

Yes. Text-to-SQL turns a plain question into a database query, and the rows the database returns are the facts the model uses. It gives exact numbers straight from the database, but the model must know the schema, and every query must be checked before it runs.

11 min readIntermediateCommon · estimateFacts checked 26 November 2026

Say it out loud

Read it once, then say it without looking. Start with the short one; use the long one when they ask you to go deeper.

Yes, I count it as retrieval. A text-to-SQL assistant turns a plain question into a SQL query, the database runs it, and the rows that come back are the facts the model uses to answer. Vector search finds text that sounds similar. Text-to-SQL gets exact numbers from the database, so last quarter's payouts come from a real total. The risks are a wrong join that looks right, and a query that changes data. So I give the model a read-only login and check every query first.

What is text-to-SQL, in plain words?

Text-to-SQL means a model turns your question into a SQL query. SQL is the common language for asking a database for rows.

Think of a new hire at a bank. They don't guess a balance. They ask the records team for a printout, then explain what it says.

A real case: a claims team at a mid-size insurer asks, "What did we pay on Ohio auto claims in Q3?" The assistant writes the query, and the insurer's own database returns the total.

Key words

Text-to-SQL
A model writes a SQL query from a plain question, and a database runs it.
Schema
The list of tables and columns, with their names and keys, that the model reads first.
Vector search
Finds passages that match in meaning. RAG systems can use it.
Read-only login
A database account that can read rows but can't change or delete them.

How is it different from vector search?

Vector search is one way to do it. It turns text into numbers that capture meaning, then finds passages close to the question.

Text-to-SQL suits facts that live in tables: totals, counts, dates and filters. A passage can say payouts rose. Only a query can add up the rows behind that claim.

  • Vector search

    Finds similar text

    Good for policies, manuals and notes. Returns passages with no exact totals.

  • Text-to-SQL

    Runs a real query

    Good for numbers and filters. Returns exact rows straight from the database.

  • The catch

    The model must see the schema

    A wrong join still returns a clean table, so the numbers can look right and be wrong.

Two ways to get the facts

Your question

in plain English

Vector search

Find similar passages

matches by meaning

Text-to-SQL

Model writes SQL

reads table and column names

Database runs it

adds up exact rows

Passages

read, then paraphrased

Exact rows

the numbers, as stored

Answer

numbers from the rows can be checked

  1. 1Your question goes down both paths.
  2. 2The model reads the table names and writes a SQL query.
  3. 3The database runs that query on the real tables.
  4. 4Similar passages go into the prompt.
  5. 5The database hands back the exact rows the query selected.
  6. 6The passages reach the model, which writes the answer.
  7. 7The rows reach the model too, and the answer cites them.
Both paths start from one question. Vector search pulls passages. Text-to-SQL writes a query that the database runs, and its answer can point back to exact rows.

How much does the schema matter?

The model can only write good SQL if it knows which tables and columns exist. Microsoft's Copilot for SQL database says it uses table and column names, plus the primary and foreign keys that join them. A key is a column that ties one table to another, so a join matches rows on those keys.

Spider 2.0, a shared test set (a benchmark) whose databases come from real data applications, says they often have over 1,000 columns.

  • “Copilot for SQL database uses table and view names, column names, primary key, and foreign key metadata to generate T-SQL code.”

    Microsoft, Azure SQL Database docs

So retrieve the schema first. Send only the tables that match the question.

The BIRD benchmark (a shared test set for text-to-SQL), from 2023, names the same kind of problem. Its authors list dirty database contents, external knowledge and SQL efficiency as new challenges.

How does one question get answered?

Here is the Ohio question from start to finish, with made-up numbers, on one table of five columns.

  1. 1

    Send the schema

    Only the claims table goes in, with its column names. Other tables stay out of the prompt.

  2. 2

    The model writes one query

    It filters on state, line and quarter, then adds up the paid amounts.

  3. 3

    Code checks it

    It must start with SELECT. It runs under the read-only login and stops at the row limit.

  4. 4

    The database returns one row

    The total is 6,050.50. The answer quotes that total and shows the query next to it.

The code below runs the same idea with Python's built-in sqlite3 database. It shows the query, the rows it returns, and a write that gets refused.

Python
import sqlite3

# A made-up claims table, the kind an insurer's claims team queries
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE claims (id INTEGER, state TEXT, line TEXT, quarter TEXT, paid REAL)")
db.executemany("INSERT INTO claims VALUES (?, ?, ?, ?, ?)", [
    (1, "OH", "auto", "Q3", 4200.0),
    (2, "OH", "auto", "Q3", 1850.5),
    (3, "OH", "auto", "Q2", 9100.0),
    (4, "PA", "auto", "Q3", 2300.0),
])

def run_query(sql):
    # First gate only: a string check. The real gate is a read-only database login.
    if not sql.lower().startswith("select"):
        return "REFUSED: only SELECT is allowed"
    return db.execute(sql).fetchall()

# The model wrote this SQL for the question: what did we pay on Ohio auto claims in Q3?
sql = "SELECT ROUND(SUM(paid), 2) FROM claims WHERE state = 'OH' AND line = 'auto' AND quarter = 'Q3'"
print("Rows:", run_query(sql))
print(run_query("DELETE FROM claims WHERE quarter = 'Q2'"))

Output

Rows: [(6050.5,)]
REFUSED: only SELECT is allowed

The total is exact because the database added it up. The string check is only a first gate. The real one is the read-only login, since a text check can be fooled by clever wording.

Where does it go wrong, and how do you limit it?

The main risks are a wrong join that looks clean, a query that changes data, and rows that carry hidden instructions. That last one is prompt injection, where text inside the data tries to give the model new orders. OWASP's 2026 list of AI risks says there is "no clean equivalent to parameterized queries" (queries that keep data apart from the SQL text), because LLMs "make no architectural distinction between" instructions and data. So the escape step that protects SQL cannot fix it.

The controls sit in code and in the database, not in the prompt. The model never holds the database password.

  1. 1

    Read-only login

    An account that can only read, so the database itself refuses a DELETE.

  2. 2

    Row and time limits

    A runaway query is cut off, so it cannot tie up the reporting server.

  3. 3

    Allowed tables only

    Payroll and HR tables are not on the list, so a clever question cannot reach them.

  4. 4

    Test with signed-off answers

    Keep questions with totals the finance team has signed off, and rerun them after each change.

Checks around a generated query

Question

from a staff member

Model writes SQL

a suggestion until code agrees

Code checks it

Read-only login

cannot change or delete rows

Row and time limits

a runaway query stops early

Allowed tables only

payroll stays out of reach

Runs, SQL shown

the SQL sits beside the answer

Refused

a write or a banned table

  1. 1The question goes to the model, with the table names it needs.
  2. 2The model returns SQL, which is only a suggestion.
  3. 3Code checks the query. A clean one runs.
  4. 4A write, or a table outside the list, is refused.
The model's SQL is treated as a suggestion. Code and the database check the query first: a read-only login, row and time limits, and an allowed-table list. A write or a banned table is refused, even if the model was fooled.

A prompt that says do not write to the database is a soft layer. It lowers the odds, but OWASP notes that filters which judge meaning can be evaded by rephrasing or encoding.

What does the interviewer want to hear?

A strong answer covers

  • A plain answer: yes, it retrieves exact rows instead of text passages.
  • Why it helps: totals and filters come straight from the database.
  • What the model sees: the schema, not every row.
  • The risks: wrong joins, writes, and rows that carry hidden instructions.
  • Limits in code: a read-only login, row limits, allowed tables, checks.
  • How you measure it: questions with signed-off answers, run on every change.

Common traps

  • Trap"The model runs the query itself."

    BetterThe model only writes the text. Your code runs it, under a read-only login.

  • Trap"SQL is exact, so the answer is always right."

    BetterThe SQL can still ask the wrong question. Check the joins and test with known answers.

  • Trap"Give the model the whole database."

    BetterSend only the tables this question needs. Big schemas can confuse the model and cost more, since you pay per token (a small chunk of text).

Can you spot the risky query?

Spot the risky query

The model wrote four queries for the claims team. Which one is a problem?

Quick check

Why is a database total more trustworthy than a passage that says payouts rose?

Can you answer these from memory?

Flash cards · tap a card to flip it

1 / 5

What will they ask next?

  1. Q151"The answer was in the docs, but the bot missed it." How do you debug?12 min
  2. Q152How do you handle conflicting sources?Coming soon
  3. Q154Sparse vs dense embeddings?Coming soon
  4. Q156What is tool (function) calling?11 min
  5. Q360Design a text-to-SQL analytics assistant.Coming soon

Learn it in depth

Last updated on 26 November 2026

Building an assistant that answers from your company's data?

I design and build AI assistants that query real data, with the limits kept in code: read-only access, checked queries and tests with signed-off answers. Book a short call and tell me what your data looks like.