Text-to-SQL with LLMs: how to ship natural-language analytics without wrong numbers or data leaks
How to build a text-to-SQL feature for your SaaS product: why benchmark accuracy overstates production accuracy, the semantic layer that fixes it, and the database permissions that contain the risk.
Every SaaS founder has seen the demo: a text box that says "ask your data
anything", and a chart appears. Text-to-SQL with LLMs is genuinely
useful, and it is also the AI feature most likely to put a wrong number in
front of a customer who will act on it. The query that runs without error and
returns the wrong figure is worse than the one that fails.
This post covers why demo accuracy does not survive contact with a real schema,
the layer that fixes most of it, and the database controls that make the
feature safe to expose to customers.
Why does text-to-SQL work in demos and fail in production?
Because demo databases are small and self-explanatory. The Spider 1.0
benchmark that made text-to-SQL look solved used compact schemas. Its
successor, Spider 2.0, is built from real
enterprise workflows, and the project reports that at launch GPT-4o solved
10.1% of tasks and o1-preview 17.1%, against 86.6% for GPT-4o on Spider 1.0.
Agentic systems now score much higher on its leaderboards, but the gap tells
you what changed: real schemas have hundreds of columns, cryptic names,
soft-deleted rows, and business rules that live in someone's head.
The failures that matter to a product are not syntax errors:
Ambiguous metrics. "Revenue" could be invoiced, collected or recognised.
The model picks one and states it with full confidence.
Wrong joins. A fan-out join double-counts; the number looks plausible.
Missing filters. Test accounts, cancelled orders and soft-deleted rows
that every human analyst knows to exclude.
Silent time handling. Time zones, fiscal years and "last month" at a
month boundary.
What should sit between the model and your tables?
A semantic layer: a curated list of metrics, dimensions and approved joins,
each defined once by someone who owns the number. The model's job shrinks from
"write correct SQL against 300 tables" to "choose the right approved metric and
filters", which is a far easier problem and one you can test.
Approach
Model writes
Accuracy risk
Audit effort
Typical fit
Raw schema, free-form SQL
Full SQL over all tables
Highest
Hard
Internal analyst tools
Curated views, free-form SQL
SQL over a few documented views
Medium
Medium
Power users, narrow domains
Semantic layer / metric definitions
A structured request (metric, group-by, filter)
Low
Easy
Customer-facing analytics
Fixed parameterised query tools
Tool name and arguments
Lowest
Easiest
Top 10-20 known questions
For a customer-facing feature, start at the bottom of the table and move up
only when logged questions show customers asking things the fixed set cannot
answer. Because the model's output is a structured request, the
reliability techniques in our post on
structured LLM output apply
directly.
How do you make LLM-generated SQL safe to run?
Assume the model will eventually emit something you did not intend, whether
from a mistake or from a prompt-injection attempt hidden in the data it reads
(see AI agent security). Then make
that harmless with controls that do not depend on the model behaving:
A dedicated role. Grant SELECT on an approved set of views only. No
access to base tables, no write privileges, no access to system tables with
other customers' metadata.
Read-only transactions. PostgreSQL's
default_transaction_read_only
makes new transactions read-only; set it on the role, not just in the
prompt.
A statement timeout.statement_timeout aborts any statement that runs
too long, and the docs note that the default of zero disables it. An
unbounded cross join on a large table is an outage, not an error.
Row and cost limits. Cap returned rows and, where your warehouse
supports it, bytes scanned per query.
Parse before you run. Reject anything that is not a single SELECT
statement using an allow-list of tables, using a real SQL parser rather than
string matching.
How do you stop one customer querying another's data?
Not with the prompt. "Only return rows for tenant 42" is an instruction, and
instructions can be argued with. Enforce it in the database. PostgreSQL's
row-level security
works for this, with a caveat that catches many teams: superusers and roles
with BYPASSRLS always bypass it, and table owners normally do too unless you
run ALTER TABLE ... FORCE ROW LEVEL SECURITY. If the analytics role is the
owner, your policies do nothing.
Set the tenant on the connection from the authenticated session, never from
anything the model produced, and write a CI test that runs hostile queries as
the real analytics role and asserts zero cross-tenant rows. The full set of
isolation options is in our post on
multi-tenant RAG data isolation; the
same reasoning applies to SQL. Also keep personal data out of the prompt: the
schema and sample rows you send for context can contain it, so apply the
controls in
LLM PII redaction.
How do you know the numbers are right?
Treat it like any other LLM feature: build an evaluation set before you ship.
Collect 50-100 real questions from your support inbox and customer calls,
each paired with a SQL query or expected answer written by a human who owns
the metric.
Score on result equivalence, not text match: two different queries can
both be right.
Re-run the set on every prompt, schema or model change; our post on
LLM evals in CI shows the
setup.
Log every production question with the generated query and the user's
thumbs-up or down. Wrong answers that users flag become new test cases.
Then design the interface to reveal the work. Show the metric definition and
the filters applied next to the number, with a "view query" option. Users
catch a wrong filter in two seconds when they can see it, and you convert a
silent error into a visible one. When the model is unsure which metric the
user meant, ask a clarifying question instead of guessing.
Should you build this or buy it?
Buying makes sense when analytics is not your product, your data lives in one
warehouse with an existing BI vendor, and your users are internal. Building
makes sense when the feature sits inside your product, results must respect
your tenancy model, and the questions are specific to your domain. The
broader trade-off is covered in
build vs buy for AI features.
What to do next
Before you build the text box:
List the 20 questions customers ask most often. If fixed query tools answer
most of them, ship those first.
Write the metric definitions down and assign an owner to each.
Create the restricted role, with a timeout and read-only default, and test
it against hostile queries.
Build the evaluation set before choosing a prompt.
Decide what the interface says when the answer is "I'm not sure".
If you are adding analytics or an "ask your data" feature to a SaaS product,
the AI SaaS page below describes how we approach multi-tenant platforms and
their data access boundaries.
CodeKrypt
Drafted by CodeKrypt's AI writing pipeline, built and maintained by our engineers, under fixed rules on sources and claims. How we write
Frequently asked questions
How accurate is text-to-SQL with LLMs on real company databases?
Much lower than on classic benchmarks. The Spider 2.0 benchmark, built from real enterprise workflows, reported GPT-4o at 10.1% and o1-preview at 17.1% at launch, against 86.6% for GPT-4o on the older Spider 1.0. Agentic systems have since scored far higher on its leaderboard, but your own schema, with its own naming quirks, is the only test that matters.
What is a semantic layer and why does text-to-SQL need one?
A semantic layer is a curated, named set of metrics, dimensions and joins, such as 'monthly recurring revenue' defined once. Letting the model pick from approved definitions instead of inventing SQL over raw tables removes the most common source of confidently wrong numbers: disagreement about what a metric means.
Is it safe to let an LLM run SQL against a production database?
Only behind several independent controls: a dedicated database role with SELECT on approved views only, read-only transactions, a statement timeout, row limits, and tenant isolation enforced by the database rather than by the prompt. Never rely on the model being told not to write or not to read other tenants' rows.
Should the model write SQL or call a fixed set of query tools?
For most B2B products, start with parameterised query tools or a semantic layer for the top questions and allow free-form SQL only over a narrow set of views. Free-form SQL is flexible and hard to audit; fixed tools are the reverse.
Does row-level security protect text-to-SQL queries?
Yes, if the connection uses a role that is subject to it. PostgreSQL documents that superusers, roles with BYPASSRLS and table owners bypass row security, so the query role must be none of those, or the table must use FORCE ROW LEVEL SECURITY.
An AI feature SLO needs more than uptime. Which indicators to measure, which to put in a contract, and how to keep a provider outage or a quality drift from becoming your SLA breach.
Adding AI to an existing app does not require a rewrite. How to pick the first feature, put an AI layer beside your legacy system, and keep failures from reaching users.
How to roll out an LLM prompt or model change without surprising users: shadow mode, canary releases and A/B tests, what each answers, what each costs, and the gates between them.