Text-to-SQL With LLMs: Build a Natural Language Database Query Tool
Build a text-to-SQL tool with LLMs: train Vanna on your schema, ask questions in plain English, and add guardrails keeping generated SQL safe. Tutorial inside.
By Galactic News Editorial · Published 2026-11-18T10:33:21+00:00 · Updated 2026-11-18T10:33:21+00:00
Text-to-SQL with LLMs turns a plain English question into a working database query. Ask "which product category had the highest revenue last year?" and get SQL back, run it, and read the answer. This tutorial builds a small natural language database query tool with Vanna, the open-source Python framework. You will train it on a schema, ask questions, and add the guardrails that keep it safe.
How a text to SQL LLM tool works
The LLM never sees your raw data. It sees context: table definitions, column types, business terms, and example queries. That context is what makes the SQL correct. Vanna uses retrieval-augmented generation. You train it on DDL statements, documentation, and past SQL. When a question arrives, Vanna finds the most relevant training data and includes it in the prompt. The LLM writes SQL from that prompt. The SQL runs in your own environment, and the results come back.
Three parts make the system work. The schema context tells the model which tables and columns exist. The training data teaches it your business terms, like what "active customer" means. The validation layer checks the SQL before it runs. Skip any of the three and the tool will produce confident, wrong queries. That is the main failure mode of every text-to-SQL demo.
Step 1: Choose your stack
Pick Vanna if you want a focused framework with a simple train-and-ask flow. Pick a LangChain SQL agent if you want the model to explore the schema itself and retry when a query fails. Pick a hosted product like Wren AI or AskYourDatabase if you do not want to maintain the stack. This tutorial uses Vanna because it is the smallest path to a working tool. Vanna is an MIT-licensed open-source Python framework. It works with any SQL database you can connect to from Python, and with many LLMs and vector databases.
Install the base package and the pieces for your database. For SQLite and OpenAI with ChromaDB as the vector store, the install looks like this:
pip install 'vanna[chromadb,openai,sqlite]'
Check the official Vanna docs for your exact database. The package names change with the database and the LLM you choose.
Step 2: Set up a demo database
Start with SQLite. It needs no server and it is easy to reset. Create a small database with two or three tables that mirror a real problem. A customers table, an orders table, and a products table are enough. Load a few hundred rows of sample data. Keep the data realistic but fake. Never train on production data in a demo.
Write the DDL for each table and keep it in a file. You will feed the same DDL to Vanna in the next step. If your real schema is large, limit the tables the tool can see. LangChain's SQL integration offers the same advice: use an include list to limit schema exposure on large databases. A model that sees fifty tables will join the wrong ones.
Step 3: Train Vanna on your schema
Training is three calls. First, train on the DDL so the model knows the tables and columns. Second, train on documentation: short sentences that define business terms. Third, train on example SQL for the questions your team asks most. Vanna's own docs show this pattern:
from vanna.openai import OpenAI_Chat
from vanna.chromadb import ChromaDB_VectorStore
class MyVanna(ChromaDB_VectorStore, OpenAI_Chat):
def __init__(self, config=None):
ChromaDB_VectorStore.__init__(self, config=config)
OpenAI_Chat.__init__(self, config=config)
vn = MyVanna(config={'api_key': 'sk-...', 'model': 'gpt-4o'})
vn.train(ddl="CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT, signup_date DATE)")
vn.train(documentation="An active customer placed an order in the last 90 days.")
vn.train(sql="SELECT name FROM customers WHERE signup_date > '2026-01-01'")
Each time you ask a question, Vanna retrieves the most relevant training data and adds it to the prompt. The docs describe the default as pulling the ten most relevant items. Good training data is the difference between a tool that works and a demo that fails on the second question. Add the queries your team actually runs, not generic examples.
Step 4: Ask questions and check the SQL
Ask a question and read the SQL before you trust the answer:
sql = vn.generate_sql("Which product category had the highest revenue last year?")
print(sql)
Check three things in every generated query. Does it join the right tables? Does it filter the right date range? Does it aggregate the right column? Then run it and check the result against a query you wrote by hand. Do this for your ten most common questions. Log the ones that fail. Each failure is training data: add the corrected SQL and ask again.
Step 5: Add guardrails before anyone else uses it
A text-to-SQL tool without guardrails is a risk. Add these five before you share it with a team. First, use a read-only database user. The tool should never be able to write, update, or delete. Second, block dangerous statements. Reject any generated SQL containing DROP, DELETE, UPDATE, INSERT, or ALTER. Third, cap the rows. Add a LIMIT to every query and a timeout. Fourth, restrict the tables. The tool should only see the tables its users are allowed to query. Fifth, log every question and every query. The log is your audit trail and your training data for the next round.
Vanna's design helps here. SQL execution happens in your local environment, not on a vendor server. Database contents are not sent to the LLM or the vector database. That keeps the data inside your boundary. The LLM still sees schema and examples, so keep sensitive column names out of the training data.
Text to SQL LLM options compared
| Approach | How it works | Strength | Weakness |
|---|---|---|---|
| Vanna | RAG over DDL, docs, and example SQL | Simple train-and-ask flow; any database | Needs good training data to be accurate |
| LangChain SQL agent | Agent explores schema, writes and retries SQL | Flexible; self-corrects on errors | More failure modes; no dashboards or alerts |
| Hosted tools (Wren AI, AskYourDatabase) | Managed text-to-SQL over a live database | No maintenance; dashboards included | Less control; subscription cost |
| Raw LLM prompting | Paste DDL into a prompt and ask for SQL | Zero setup | No memory, no validation, no safety |
Bottom line
Start with Vanna on SQLite and ten real questions from your team. Train on your DDL, your business terms, and your existing SQL. Check every generated query by hand until ten in a row are correct. Then add the guardrails: read-only access, blocked write statements, row limits, table restrictions, and full logging. A text-to-SQL tool earns trust one correct query at a time. Ship the guardrails first and the chat interface second.