All posts

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.

CodeKrypt 6 min read

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:

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.

ApproachModel writesAccuracy riskAudit effortTypical fit
Raw schema, free-form SQLFull SQL over all tablesHighestHardInternal analyst tools
Curated views, free-form SQLSQL over a few documented viewsMediumMediumPower users, narrow domains
Semantic layer / metric definitionsA structured request (metric, group-by, filter)LowEasyCustomer-facing analytics
Fixed parameterised query toolsTool name and argumentsLowestEasiestTop 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.

Flow from user question to LLM, to a structured metric request, to a validator, to a read-only database role, to a result with the generated query shownQuestionLLMMetric request(validated)Read-onlyDB roleAnswer + thequery shownThe model never holds credentials; the validator and the database enforce the rules.

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:

  1. 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.
  2. Read-only transactions. PostgreSQL's default_transaction_read_only makes new transactions read-only; set it on the role, not just in the prompt.
  3. 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.
  4. Row and cost limits. Cap returned rows and, where your warehouse supports it, bytes scanned per query.
  5. 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.

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:

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 avatar

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.

Related reading

Chat on WhatsApp