# 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.

AI and LLM interview question Q153, Retrieval-augmented generation (RAG). Intermediate, common (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/text-to-sql-as-retrieval

## Say it in 30 seconds

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.

## Say it in 2 minutes

Retrieval means fetching the facts a model needs, then putting them in its prompt. RAG (retrieval-augmented generation) systems can do it with vector search, which finds passages that are similar in meaning. Text-to-SQL does it differently. The model reads the database's table and column names, writes a SQL query, and the database runs it. The rows that come back are the retrieved context.

That makes it a good fit for numbers and filters: totals, counts, dates and anything in a table. Vector search finds a paragraph about claim payouts. It cannot add up 40,000 rows; the database can. The cost is that the model has to know the schema, and a join on the wrong key still returns a clean table of wrong numbers. A good first test is a question whose answer you already know, to see whether the query gets it.

So I limit the damage. The model gets a read-only login, a row limit, and only the tables the question needs. Code checks the query before it runs, and the SQL is shown next to the answer, so a reviewer can read the join and the filter in a minute. I test with questions whose right answers a finance team has already signed off.

## 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.

- **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.

*Diagram, Two ways to get the facts: 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.*
1. Your question goes down both paths.
2. The model reads the table names and writes a SQL query.
3. The database runs that query on the real tables.
4. Similar passages go into the prompt.
5. The database hands back the exact rows the query selected.
6. The passages reach the model, which writes the answer.
7. The rows reach the model too, and the answer cites them.

## 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. **Send the schema:** Only the claims table goes in, with its column names. Other tables stay out of the prompt.
2. **The model writes one query:** It filters on state, line and quarter, then adds up the paid amounts.
3. **Code checks it:** It must start with SELECT. It runs under the read-only login and stops at the row limit.
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:

```text
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. **Read-only login:** An account that can only read, so the database itself refuses a DELETE.
2. **Row and time limits:** A runaway query is cut off, so it cannot tie up the reporting server.
3. **Allowed tables only:** Payroll and HR tables are not on the list, so a clever question cannot reach them.
4. **Test with signed-off answers:** Keep questions with totals the finance team has signed off, and rerun them after each change.

*Diagram, Checks around a generated query: 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.*
1. The question goes to the model, with the table names it needs.
2. The model returns SQL, which is only a suggestion.
3. Code checks the query. A clean one runs.
4. A write, or a table outside the list, is refused.

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." Better: The model only writes the text. Your code runs it, under a read-only login.
- Trap: "SQL is exact, so the answer is always right." Better: The SQL can still ask the wrong question. Check the joins and test with known answers.
- Trap: "Give the model the whole database." Better: Send 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?

A. SELECT SUM(paid) FROM claims WHERE state = 'OH' AND quarter = 'Q3'
B. SELECT id, paid FROM claims WHERE state = 'PA' AND quarter = 'Q3'
C. UPDATE claims SET paid = 0 WHERE quarter = 'Q3'
D. SELECT COUNT(*) FROM claims WHERE quarter = 'Q3'

**Answer:** C. The third query changes rows. A read-only login refuses it, and so would a check on the first word. The other three only read data.

**Quick check:** Why is a database total more trustworthy than a passage that says payouts rose?

A. The database adds up the exact rows itself
B. Passages cannot contain any numbers
C. SQL answers always come back faster
D. The model reads the total out of the passage

**Answer:** A. The database does the arithmetic on the real rows. A passage only tells a story, and a model adding up numbers from text can slip.

## Can you answer these from memory?

**Flash cards**

- **What is text-to-SQL?** The model writes a SQL query, and the database runs it. The rows are the retrieved context.
- **What must the model see?** The schema: table and column names, plus the primary and foreign keys.
- **Why is a wrong join dangerous?** It still returns a clean table, so the wrong number looks right.
- **What stops a query that writes data?** A read-only login, enforced by the database, plus code checks before the query runs.
- **How do you test a text-to-SQL assistant?** With questions whose answers a finance team has already signed off, comparing the numbers.

## Likely follow-up questions

- Q151 "The answer was in the docs, but the bot missed it." How do you debug? https://designervenkat.online/interview/ai/debug-a-rag-bot-that-missed-the-answer
- Q152 How do you handle conflicting sources? (full answer coming)
- Q154 Sparse vs dense embeddings? (full answer coming)
- Q156 What is tool (function) calling? https://designervenkat.online/interview/ai/what-is-tool-calling
- Q360 Design a text-to-SQL analytics assistant. (full answer coming)

## Learn it in depth

- [Where RAG fits, and where not](https://designervenkat.online/learn/ai-engineering/rag-usecases)
- [From question to context](https://designervenkat.online/learn/ai-engineering/retrieval-process)
