Search Tutorials
--Ads--Retrieving from SQL Databases (Text-to-SQL)
Answer questions over structured data by generating and running safe SQL queries.
Some questions cannot be answered by retrieving text: "What was our total revenue in Q3?", "Which five customers placed the most orders this year?", "How many tickets are still open?". The answer is a calculation over structured data. Embedding database rows and retrieving a few of them gives wrong totals. Instead, let the LLM write a SQL query, run it safely, and answer from the result. This is Text-to-SQL.
The pipeline
- Give the LLM the database schema (tables, columns, types, short descriptions) and the question.
- The LLM returns a SQL query.
- Your code validates the query and runs it with a read-only connection.
- The LLM writes the final answer from the query result.
Sample database
import sqlite3
conn = sqlite3.connect("shop.db")
conn.executescript("""
DROP TABLE IF EXISTS orders; DROP TABLE IF EXISTS customers;
CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT, city TEXT, signup_date TEXT);
CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER REFERENCES customers(id),
order_date TEXT, amount_inr REAL, status TEXT);
INSERT INTO customers VALUES (1,'Asha Traders','Pune','2025-02-11'), (2,'Nova Retail','Delhi','2025-06-03'),
(3,'Kiran Stores','Pune','2026-01-20');
INSERT INTO orders VALUES (1,1,'2026-07-02',12500,'delivered'), (2,2,'2026-07-15',8400,'delivered'),
(3,1,'2026-08-09',23000,'shipped'), (4,3,'2026-09-21',5600,'cancelled'),
(5,2,'2026-09-30',17800,'delivered');
""")
conn.commit()
conn.close()
Generate SQL with a structured output
import sqlite3
from pydantic import BaseModel
import anthropic
client = anthropic.Anthropic()
SCHEMA = """Table customers(id INTEGER PRIMARY KEY, name TEXT, city TEXT, signup_date TEXT 'YYYY-MM-DD')
Table orders(id INTEGER PRIMARY KEY, customer_id INTEGER -> customers.id, order_date TEXT 'YYYY-MM-DD',
amount_inr REAL 'order value in rupees', status TEXT 'delivered | shipped | cancelled')
Notes: revenue means the sum of amount_inr for orders that are not cancelled."""
class SqlQuery(BaseModel):
sql: str
explanation: str
def generate_sql(question: str) -> SqlQuery:
response = client.messages.parse(
model="claude-opus-5-5",
max_tokens=2000,
output_config={"effort": "medium"},
system=f"You write SQLite queries for this database:\n{SCHEMA}\n"
"Write a single SELECT statement. Never modify data. Add LIMIT 100 unless aggregating.",
messages=[{"role": "user", "content": question}],
output_format=SqlQuery,
)
return response.parsed_output
Run it safely
Never run LLM-generated SQL with a connection that can write. Use defence in depth:
- a read-only connection (a read-only database user in PostgreSQL or MySQL,
mode=roin SQLite), - a check that the statement is a single
SELECT, - row limits and a query timeout,
- access to only the tables and views the assistant needs.
import re
FORBIDDEN = re.compile(r"\b(insert|update|delete|drop|alter|create|attach|pragma|replace)\b", re.I)
def run_readonly(sql: str, max_rows: int = 100) -> tuple[list[str], list[tuple]]:
statement = sql.strip().rstrip(";")
if ";" in statement or not statement.lower().startswith(("select", "with")) or FORBIDDEN.search(statement):
raise ValueError(f"Refusing to run: {sql}")
conn = sqlite3.connect("file:shop.db?mode=ro", uri=True) # read-only at the driver level
try:
cursor = conn.execute(statement)
columns = [c[0] for c in cursor.description]
return columns, cursor.fetchmany(max_rows)
finally:
conn.close()
Answer from the result
from rag_helpers import ask
def answer_with_sql(question: str) -> str:
query = generate_sql(question)
try:
columns, rows = run_readonly(query.sql)
except Exception as error:
return f"I could not answer that from the database ({error})."
table = "\n".join([" | ".join(columns)] + [" | ".join(map(str, r)) for r in rows])
return ask(
f"Question: {question}\n\nSQL used:\n{query.sql}\n\nResult:\n{table}\n\n"
"Answer the question from the result only. Format money in rupees. "
"If the result is empty, say that no matching data was found."
)
print(answer_with_sql("What was our revenue in July 2026, and which customer contributed most?"))
Revenue in July 2026 was ?20,900 from two delivered orders. Asha Traders contributed the
most, with a ?12,500 order on 2 July.
Show the SQL to users who can read it, or log it. It makes answers auditable and errors easy to spot.
Improving accuracy
- Describe the schema well. Column descriptions, units, allowed values and business definitions ("revenue excludes cancelled orders") matter more than anything else.
- Add example queries for common questions to the system prompt.
- Retry on errors. If the database returns an error, send the error back to the LLM and ask for a corrected query (one or two retries).
- Large schemas: retrieve only the relevant table descriptions with vector search first, then generate SQL. This is RAG for the schema itself.
- Use views to give the model simpler, pre-joined tables with friendly column names.
To decide automatically whether a question needs SQL or document search, see Query Routing.
Key takeaways
- Use Text-to-SQL for aggregate and analytical questions over structured data, not vector search.
- Give the LLM a well-described schema and get the SQL back as structured output.
- Run generated SQL only through read-only connections with statement checks, row limits and timeouts.
- Answer from the query result and keep the SQL for transparency.