RAG Over SQL Databases: Querying Tables With an LLM Instead of Vectors
RAG over SQL databases turns plain-English questions into answers. Here is how the pipeline works, when it beats vector search, and the security rules.
By Galactic News Editorial · Published 2026-11-20T07:33:34+00:00 · Updated 2026-11-20T07:33:34+00:00
RAG Over SQL Databases: Querying Tables With an LLM Instead of Vectors
RAG over SQL databases lets users ask questions in plain English and get answers from relational tables. The LLM writes a SQL query, the database runs it, and the LLM turns the rows into a readable answer. No vector store is needed for the data itself. This guide explains how the pattern works, when it beats vector search, which tools to use, and the security rules that keep it safe.
What RAG over SQL databases means
Retrieval-augmented generation usually means vector search. Documents are embedded, stored in a vector database, and retrieved by similarity. RAG over SQL databases swaps the retrieval step. The retriever is the database itself. The LLM generates SQL, the database executes it, and the result rows become the context for the answer.
The pattern has a different name in many codebases: text-to-SQL. LlamaIndex calls it text-to-SQL and ships a query engine for it. LangChain offers chains that build SQL from natural language and optionally execute it. Vanna is an open-source Python RAG framework for SQL generation that trains on a database schema and generates SQL from questions.
This approach fits a specific kind of data. Tables hold facts. Sales by region. Orders by month. Users by plan. When the question is about numbers, counts, sums, or filters, a SQL query gives an exact answer. A vector search over exported rows would give an approximate one. Exact answers beat approximate ones for business data.
How the pipeline works
The pipeline has five stages. Each one is simple on its own. Together they form a reliable question-answering system.
- Connect to the database. Use a SQLAlchemy engine or a similar connector. LlamaIndex wraps this in a SQLDatabase object, a light wrapper around SQLAlchemy. List only the tables the application needs. Excluding tables keeps the schema context small.
- Give the LLM the schema. The prompt includes table names, column names, column types, and foreign keys. LlamaIndex builds this description automatically from the database metadata. Good column names and comments help a lot. A column called customer_id is clear. A column called c1 is not.
- Generate the SQL. The LLM reads the question and the schema, then writes a query. LlamaIndex's NLSQLTableQueryEngine does this in one step. LangChain's create_sql_query_chain builds the query without executing it. Separating generation from execution matters for safety, because the query can be checked before it runs.
- Execute and validate. Run the query against the database. Check it before execution if possible. Reject anything that is not a read-only SELECT. Reject queries that touch tables outside the allowed list. Log every query for audit.
- Synthesize the answer. The LLM receives the question, the SQL, and the result rows, then writes a plain-language answer. LlamaIndex's query engine returns both the answer and the SQL query in the response metadata, so the application can show the user exactly what ran.
RAG over SQL databases vs vector search
The two approaches solve different problems. Vector search is best for unstructured text. SQL RAG is best for structured facts. Many production systems use both, routing each question to the right engine. LlamaIndex even documents a SQL router query engine that routes to either a SQL database or a vector database, plus a SQL auto vector query engine that combines insights from structured tables with unstructured data.
| Question type | RAG over SQL | Vector search |
|---|---|---|
| How many orders shipped last month? | Exact count from a SQL query | Approximate; depends on which rows were retrieved |
| Total revenue by region in Q3? | Exact sum and grouping from SQL | Cannot compute reliably over many rows |
| What does the refund policy say? | Poor fit; policy text lives in documents | Strong fit; retrieves the relevant passage |
| Which customers churned and why? | Exact list from the database; reasons need documents | Reasons from support tickets and notes |
| Freshness of answers | Always current; queries run live | Current only if the index was rebuilt recently |
| Hallucination risk | Low for numbers; the database computes them | Higher; the model may invent figures |
The rule is simple. If the answer is a number, a list, or a filter over rows, use SQL. If the answer lives in prose, use vectors. If the question needs both, build a router that sends each part to the right engine.
Tools: LlamaIndex, LangChain, and Vanna
LlamaIndex is the most direct starting point. Its NLSQLTableQueryEngine performs text-to-SQL over a SQLDatabase object. For larger schemas, the SQLTableRetrieverQueryEngine retrieves only the relevant tables at query time, which keeps the prompt small. The official guide warns that executing arbitrary SQL is a security risk and recommends precautions such as restricted roles, read-only databases, and sandboxing.
LangChain offers two paths. The create_sql_query_chain function builds a SQL statement from text without executing it. The SQLDatabaseChain builds and executes the query in one step. LangChain's own documentation warns that the execution path is susceptible to SQL injection and that queries must be validated before execution. Prefer the generation-only chain, validate the SQL, then execute it yourself.
Vanna takes a different approach. It trains a RAG model on database metadata: DDL statements, documentation, and historical SQL queries. The metadata is embedded and indexed in a vector database. At query time, the relevant metadata is retrieved and used as context for the LLM to generate SQL. Vanna supports any SQL database and can be extended to any LLM and vector database. It also offers interfaces for Jupyter Notebook, Streamlit, Flask, and Slack.
Start with LlamaIndex for a first prototype. Its query engine is a few lines of code and works with SQLite or DuckDB locally. Move to Vanna when the schema is large or when the team needs to train on historical queries. Use LangChain when the SQL step is one part of a larger agent workflow.
Security rules you cannot skip
Text-to-SQL is a code generation feature. The LLM writes code that runs against a production database. That makes security the first design decision, not an afterthought.
Use a read-only database user. The connection the LLM queries through should have SELECT permission and nothing else. No INSERT, UPDATE, DELETE, or DROP. If the generated SQL tries to write, the database refuses it.
Restrict the tables. Include only the tables the application needs. Exclude tables with passwords, tokens, personal data, or financial secrets. LlamaIndex's SQLDatabase accepts an include_tables list for exactly this purpose.
Validate the SQL before execution. Parse it. Confirm it is a single SELECT statement. Reject anything with a semicolon followed by another statement. Reject keywords such as DROP, DELETE, UPDATE, INSERT, and ALTER. A simple allowlist is safer than a blocklist.
Limit the damage. Cap result rows. Set a query timeout. Run the database in a sandbox or a read replica. Log every generated query with the user who asked the question. If something goes wrong, the log shows what ran and who asked.
When to use it, and when not to
Use RAG over SQL when the data is tabular, the questions are about facts and numbers, and the answers must be exact. Internal dashboards, support analytics, sales reporting, and operations questions are strong fits. The pattern shines when non-technical users need answers from a database they cannot query themselves.
Do not use it when the data is mostly prose, when the questions are open-ended, or when the schema is undocumented. A database with cryptic column names and no foreign keys will produce bad SQL. Fix the schema documentation first. Add comments to tables and columns. Name things clearly.
Do not use it as the only retrieval layer for a general assistant. Pair it with vector search for documents. A router that sends number questions to SQL and text questions to vectors covers far more ground than either alone.
Bottom line
RAG over SQL databases turns plain-English questions into exact answers from relational tables. The LLM writes the SQL, the database computes the result, and the LLM explains it. LlamaIndex offers the fastest prototype, LangChain fits larger agent workflows, and Vanna handles large schemas with trained retrieval. The pattern is powerful, but only with a read-only user, restricted tables, and SQL validation before execution. Get those three controls right and the system is both useful and safe.