Natural Language Questions Over A SQL Database
The question that keeps coming back
Every company with a database has a person who gets asked the same kind of question several times a week. How many customers signed up last month? Which plan has the most cancellations? What was revenue from the Singapore office in the second quarter? The person who knows SQL stops what they’re doing, writes a query, pastes a number into a chat, and goes back to their actual job.
Letting people ask those questions in plain English and having a model write the query is one of the most requested AI features inside companies. It’s also one where the demo and the production system are very far apart. In a demo, the model writes a neat query against a clean sample schema and the right number comes back. In production, the model is writing code that runs against real data, with real access rights, on tables whose names made sense to someone in 2019.
This piece is about doing that safely. The safety here has two halves. One is the obvious one: the model must not be able to change or delete anything, or read what the person asking shouldn’t see. The other is quieter and causes more damage in practice: the model writes a query that runs perfectly, returns a plausible number, and the number is wrong. Most of the work in a text to SQL system goes into the second half.
It’s a different problem from retrieval over documents. There’s no chunking and no embedding search over passages. The model is generating a program, and the database executes it. That changes what can go wrong and where the controls need to sit.
What the model actually does
The basic loop is short. Your application sends the model the user’s question along with a description of the database schema: table names, column names and types, and ideally some explanation of what they mean. The model writes a SQL query. Your code runs that query against the database and gets rows back. Often a second model call turns those rows into a sentence or a small chart.
Most implementations wire this up as a tool call. The model is given a function, something like run_query, that takes a SQL string. It decides to call it, your code executes it, and the result goes back into the conversation. Some systems let the model call it several times, looking at the result of one query before writing the next. That’s useful for questions that need exploration, and it also means more queries run per question, which matters for both cost and risk.
The model has never seen your data. It sees only the schema text you send and the results of queries it runs. Everything it knows about what cust_flg_2 means comes from you, or from guessing based on the name. That single fact explains most text to SQL failures. When it guesses right, the demo works. When it guesses wrong, it still writes a valid query.
The other fact that shapes the design is that SQL is code with side effects. A classifier that returns the wrong label moves an email to the wrong queue. A text to SQL system that returns the wrong statement could, if you let it, drop a table. So the first design decision has nothing to do with prompts at all.
Read-only lives in the database, not the prompt
The single most important control is a database role that can only read. Create a dedicated user for the assistant, grant it SELECT on exactly the tables or views it needs, and grant it nothing else. No insert, no update, no delete, no DDL, no permission to create temporary tables unless you’ve thought about it, no access to system functions that can read files or make network calls.
Telling the model “only write SELECT statements” in the prompt is not a control. It’s a request. Models follow instructions most of the time, and most of the time is not the standard for something that touches production data. A cleverly worded question, a confused model, or text inside the data itself can all produce a statement you didn’t want. The database role is the thing that makes a harmful statement fail regardless of what the model wrote.
Where you can, point the assistant at a read replica or a reporting copy rather than the primary database. That separates it from live writes entirely and means a heavy query slows down reporting rather than checkout. Many teams already have an analytics warehouse fed from production, and that’s usually the right target, since it was built for exactly this kind of ad hoc reading.
Check the role’s effective permissions after you create it. Some databases grant rights to a default public role that every user inherits, and some managed services add their own grants. Connect as the assistant’s user and try a write. Try reading a table it shouldn’t see. If either works, fix the grants before anything else, because nothing later in the pipeline can compensate for a role that has more power than you think.
Limit what the role can see
Read-only doesn’t mean harmless. A role that can read the entire database can answer “list every customer’s email and phone number” as happily as “how many customers do we have”. The model will leak exactly what the role can read, so the role should read as little as the questions need.
The cleanest way to do that is to build views for the assistant rather than granting access to raw tables. A view can leave out sensitive columns entirely, such as personal contact details, payment tokens, password hashes or free-text notes. It can pre-join tables so the model doesn’t have to discover the join path. It can filter out rows the assistant should never count, like internal test accounts. And it gives the columns clear names, which helps with the accuracy problem later.
If different users should see different data, enforce that in the database too. Row-level security, where the database supports it, lets the same query return only the rows a given user is allowed to see. The application passes the user’s identity through to the session, and the database applies the filter. That’s far safer than asking the model to add a WHERE region = 'APAC' clause for users in that region, because the model can forget, and a user can ask it not to.
Aggregates deserve a thought as well. Even if individual rows are hidden, a sequence of narrow counts can reveal them: how many customers in this postcode signed up on this date on this plan. Whether that matters depends on your data. For most internal business questions it won’t, but for anything involving health, salaries or personal data it might, and a view that only exposes aggregated tables is sometimes the right answer.
Resource limits and runaway queries
A read-only query can still hurt. A missing join condition produces a cross join that multiplies two large tables together. A query without a filter can scan years of event data. On a production database that means slow pages for customers. On a warehouse that bills by data scanned, it means an invoice.
Set a statement timeout on the assistant’s role, so any query that runs too long is cancelled by the database. Set a row limit on what your application will fetch and return, and tell the model about it so it writes aggregates rather than trying to pull whole tables into the conversation. Returning thousands of rows to a model also costs input tokens on the next call, and the model is poor at summarising large result sets reliably anyway.
Many databases can estimate a query’s cost before running it, usually with an EXPLAIN command. You can run that first and refuse queries whose estimated cost or scanned volume is above a threshold, returning a message to the model that asks it to narrow the question. Estimates aren’t exact, and you’ll have to tune the threshold on your own workload, but it catches the obvious disasters.
On warehouses with per-query billing, look for built-in controls such as a maximum bytes billed per query or per-user quotas, and set them for the assistant’s account. Check your warehouse’s documentation for what’s available, since the options differ. A default that caps any single query at a modest cost is worth more than any amount of prompt wording about writing efficient SQL.
Finally, if you allow the model to run several queries per question, cap how many. An agent that can’t find what it’s looking for will keep trying, and each attempt is another query and another model call.
The schema description is the real prompt
Once the safety controls are in place, accuracy depends mostly on how well you describe the data. The model can write correct SQL syntax without any help. What it can’t know is what your tables mean.
Column names are rarely self-explanatory. status might hold integers where 3 means cancelled. created_at might be stored in UTC while every business question is asked in local time. amount might be in cents. customers might include leads who never paid. Every one of those produces a query that runs, returns a number, and gets the answer wrong.
So write descriptions. For each table: what one row represents, and which rows to exclude for normal business questions. For each column that matters: its meaning, its unit, its time zone, and for coded columns the list of values and what they mean. For joins: the correct path between tables, especially where there are two plausible ones.
Then define business terms. The question “how many active customers do we have” depends entirely on what active means at your company. Paid in the last thirty days? Logged in? Has a subscription that isn’t cancelled? If you don’t define it, the model picks one, and different phrasings of the same question will get different definitions. Write the canonical definition as a snippet of SQL in the description, and the model will usually reuse it.
A handful of worked examples helps a lot: a real question, the correct query, and a note on why. Choose examples that show your conventions, such as the test-account filter or the currency conversion, rather than trivial counts.
This description is a document someone has to own. When a column changes meaning or a new table arrives, the description needs updating, just as a data dictionary does. The teams that get good results usually already had decent data documentation. The model makes that documentation executable.
Large schemas and picking the right tables
A small startup database might have twenty tables. A mature company’s warehouse can have thousands. You can’t paste all of them into every prompt, and even if the context window allowed it, the model would have to find the three relevant tables among thousands of distractors.
The usual approach is to select the relevant part of the schema before generating the query. One way is retrieval over table descriptions: embed every table’s description once, then at question time embed the question and include the closest matches. Another is a first model call that reads a short list of table names and one-line summaries and picks which ones to expand. Both work, and both fail in the same way: if the right table isn’t selected, the model writes a query against the wrong one, and it’ll still run.
The more reliable fix is to not expose thousands of tables at all. Most business questions touch a small set of well-modelled tables, often the same ones behind your existing dashboards. Choosing a small set of clean, documented views for the assistant, sometimes called a semantic layer, gives it a much smaller world to reason about. Questions outside it get an honest “that data isn’t available here” instead of a guess against a staging table nobody maintains.
That curation is manual work. It’s also the same work that makes your data usable by humans, so it rarely goes to waste. If a question keeps coming up that the chosen set can’t answer, that’s a signal to add a view, and you’ll have a record of the requests to justify it.
When you log questions, log which tables were selected for each one. When an answer turns out wrong, the first thing to check is whether the right tables were ever in the prompt.
Checking the query before it runs
Between the model writing a query and the database running it, your code gets a chance to inspect it. Use it.
Parse the SQL with a proper SQL parser for your dialect rather than with regular expressions. From the parse tree you can check things reliably. The statement should be a single SELECT or WITH query, not several statements separated by semicolons. It should reference only tables and views on your allowed list. It shouldn’t call functions you’ve decided to block. If any check fails, don’t run it: return a short error to the model explaining what was rejected, and let it try again, or tell the user the question couldn’t be answered.
This duplicates what the read-only role already enforces, and that’s deliberate. The role protects the data. The parser check gives you clear errors, a log of attempted violations and a place to add rules that aren’t about permissions, such as requiring a date filter on the events table or rejecting SELECT * on wide tables.
Some teams add a second model call that reviews the generated query against the question before it runs: does this SQL actually answer what was asked? It can catch obvious mismatches, like a query that counts orders when the question asked about customers. It’s another call’s worth of cost and latency on every question, and it’s the same kind of model judging the same kind of output, so treat it as a filter rather than a guarantee.
For questions that will be reused, such as a weekly metric someone asks for repeatedly, the strongest check is a human. Once someone who knows the data has confirmed a query is right, save it and reuse it rather than regenerating it every week.
Queries that run and still get it wrong
The failure that does the most damage is a query that runs cleanly and returns a believable number that is incorrect. Nothing errors. The user gets a confident sentence and makes a decision on it.
There are a few classic shapes. A join to a table with several rows per key double counts, so revenue comes back inflated. A missing filter includes test accounts, refunds or soft-deleted rows. A date filter uses the server’s time zone and shifts a month’s boundaries by several hours, which is small for most questions and large for daily ones. An average is taken over the wrong unit, such as orders instead of customers. A question about “last month” is interpreted as the last thirty days.
The model can’t notice any of these, because it can’t see that the number is wrong. It has no expected value to compare against. Your defences are indirect. Good descriptions and canonical definitions prevent many of them. Views that pre-join and pre-filter correctly prevent more, because the model can’t get a join wrong if it doesn’t have to write one.
The rest you handle by making the work visible. Show the user the query that ran, or at least a plain-language statement of the assumptions: counted paying customers, excluded test accounts, used Singapore time, last full calendar month. A person who knows the business can often spot a wrong assumption in that sentence faster than anyone could spot it in the SQL. Show the row count and the date range covered as well. A revenue figure computed over eleven days of a thirty-day month tells you something went wrong.
Encourage a habit of cross-checking any number that will drive a decision against a trusted dashboard or a person. That sounds like it undermines the point of the tool. It doesn’t. Most questions are exploratory and a rough answer is fine. The ones going into a board deck deserve a second look regardless of who wrote the query.
Questions the data can’t answer
Some questions have no answer in the database. “Why did cancellations go up in March?” needs context that isn’t in any table. “What will revenue be next quarter?” asks for a forecast, not a lookup. “How happy are our enterprise customers?” might have no data behind it at all, or only a proxy like support ticket counts.
Left to itself, a text to SQL system tends to answer anyway. It finds the nearest thing it can query, runs it, and presents the result as if it answered the question. Ask why cancellations rose and you might get a count of cancellations by month, framed as an explanation.
Give the model an explicit way out. In the instructions, tell it to say when the available tables can’t answer a question, and to say what they can answer instead. A reply such as “the data shows cancellations by month and by plan, but not the reasons customers gave; here are the counts” is far more useful than a confident non-answer.
Ambiguous questions need the same treatment. “How many users do we have?” could mean accounts, active users, paying users or seats. If your definitions don’t settle it, the better behaviour is to ask which one, or to answer with the definition stated clearly, rather than silently picking.
You can test for this directly. Put questions in your test set that the data can’t answer, and questions that are ambiguous, and check that the system declines or clarifies rather than inventing. Those cases tend to get left out of test sets because they don’t have a neat expected query, and they’re exactly where the embarrassing answers come from.
Measuring whether it works
You need a test set of real questions with known correct answers. Collect them from the people who currently ask: the chat messages to the data team, the recurring requests, the questions behind existing dashboards. For each one, have someone who knows the data write the correct query and record the result.
Compare results, not query text. Two different queries can both be correct, and a query that looks almost identical to the reference can be wrong because of one filter. Run the generated query and the reference query and check whether they return the same answer. For numbers, allow for rounding. For lists, compare the sets regardless of order. This is often called execution accuracy.
Because the data changes, pin the test to a snapshot or a fixed date range where you can, or re-run the reference queries each time you evaluate so both sides see the same data.
Break the results down. Which questions fail? Usually they cluster around a few tables with poor descriptions, a few business terms that aren’t defined, or one join that the model gets wrong. Fixing the description behind a cluster tends to fix several questions at once. Keep the unanswerable and ambiguous questions as their own category and score whether the system correctly declined.
Rerun the whole set whenever you change the prompt, the descriptions, the table selection method or the model. Provider model updates can shift behaviour without any change on your side, so rerun periodically even when you’ve changed nothing.
Turning rows into an answer
After the query runs, most systems pass the rows back to the model and ask it to write a reply. This step gets far less attention than query generation, and it has its own failure modes.
Models are unreliable at arithmetic over tables of numbers. Ask one to total a column of forty values, or to say which month was highest in a long list, and it’ll often get it right and sometimes get it quietly wrong. It may round a figure differently from how your finance team does, drop a currency, or describe a small change as a big one. None of that shows up as an error.
The fix is to do the arithmetic in SQL, not in the reply. If the user wants a total, the query should return the total. If they want the highest month, the query should sort and limit. The reply step then only has to put one or two already-computed values into a sentence, which models do reliably. Where you can, format numbers in your own code before they reach the model, with the right currency symbol and decimal places, so the model copies a finished string rather than reformatting a raw value.
Keep the result set small. A few rows of aggregates are easy to describe accurately. Hundreds of raw rows invite the model to summarise, and summaries of data it has only skimmed are where invented trends come from. If a question genuinely needs a table of results, show the table directly to the user and let the model write a single line of context above it.
Charts follow the same rule. Let your code draw the chart from the query results, and let the model pick the chart type and write the caption. A chart the model describes in words, with numbers it retyped, is one more place for an error to slip in.
Finally, keep the query and its raw result attached to the reply in your logs. When someone says the assistant gave a wrong number, you want to know whether the query was wrong or the sentence was.
Injection and the tool boundary
Two kinds of untrusted text reach the model in a text to SQL system. One is the user’s question. The other is the data itself, because query results go back into the conversation, and a text column can contain anything a customer ever typed into a form.
A user can try to talk the model into running something it shouldn’t, reading another team’s data or ignoring its limits. Text in a database field can contain instructions too, and when that row comes back as a result, the model reads it. This is the same prompt injection problem that affects any system where a model reads untrusted text, and it has the same answer: assume the model can be persuaded, and make sure being persuaded doesn’t matter.
That’s why the controls earlier in this piece all sit outside the model. The read-only role, the restricted views, row-level security keyed to the real user, the parser check, timeouts and cost limits all hold even if the model has been talked into trying something. Nothing in the prompt is a security boundary.
Keep the tool narrow as well. A single run_query function that accepts one read-only statement is easier to reason about than a general database tool with options. Don’t give the same assistant tools that send email, write files or call other APIs with the query results unless you’ve thought hard about what an injected instruction could do with that combination. Many tool calling failures come from tools with loose, overlapping definitions, and a text to SQL agent is no exception.
Where it fits, and what to do this week
Text to SQL works best for exploratory questions from people who understand the business but not the schema, over a hand-picked set of well-described tables, with answers that show their assumptions. It works poorly as an unsupervised replacement for a dashboard someone depends on, or as a way to let anyone query every table in the company.
If a question is asked every week, a dashboard or a saved query is better: it’s checked once, cheap to run, and gives the same answer every time. Use the assistant to find those questions. The log of what people ask is a ready-made list of dashboards worth building.
To start, create the read-only role and connect to a replica or warehouse. Build a small set of views that exclude sensitive columns and pre-join the common paths. Write descriptions for every table and important column, with units, time zones, coded values and canonical definitions for your core business terms. Set a statement timeout, a row limit and a cost ceiling.
Put a parser check in front of execution, and make every answer show the query or its assumptions along with the row count and date range. Collect thirty or forty real questions with correct answers, including a few the data can’t answer, and score by comparing results.
Then open it to a small group who know the data well enough to notice a wrong number, and read the question log every week. The wrong answers they catch will point straight at the descriptions that need work.
For more breakdowns of how AI tools behave on real workloads, and what they cost once they’re running, head back to the AI Tool Gazette homepage.