Home / Insights / Generative AI and LLMs

Generative AI and LLMs

Text-to-SQL and Natural-Language Analytics: Where It Works and How to Keep It Safe

Letting staff ask questions of company data in plain English is one of the most requested generative AI features, and one of the easiest to get wrong. This guide explains where text-to-SQL genuinely works, where accuracy collapses, and the controls that make it safe to put in front of users.

TopicsGenerative AI and LLMsAI and Machine LearningWeb and SaaS Development

Key takeaways

  • Text-to-SQL works best on a narrow, well-documented semantic layer of curated views, not on the raw production schema.
  • Public benchmarks flatter the technology: the Spider 2.0 authors report that a strong model solved only 21.3% of realistic enterprise workflow tasks.
  • Safety must be enforced by the database, not the prompt: read-only roles, row-level security, statement timeouts and a query allow-list.
  • Show the generated SQL and the assumptions behind every answer, and route high-stakes numbers through an analyst before they reach a board pack.
  • Measure accuracy against a test set of real business questions with known answers before launch and on every model or schema change.

Every operations lead I speak to has the same wish: a box where a sales manager can type “Which accounts in Victoria shrank by more than 20% last quarter?” and get a correct answer without filing a ticket with the data team. Large language models make that look easy. Write a prompt containing the schema, ask the model to produce SQL, run it, show the result. A demo takes an afternoon.

The trouble starts after the demo. The model joins the wrong table, counts cancelled orders as revenue, or quietly returns rows a user should never see. Because the answer arrives as a confident number in a tidy table, nobody notices until a decision has been made on it.

This article is for CTOs, heads of data and product leads deciding whether to offer natural-language analytics to staff or customers. It covers where text-to-SQL works, where it does not, the architecture options and their trade-offs, the security controls that should be non-negotiable, and a rollout plan. It reflects how we approach these builds in our Generative AI Development work, where grounding outputs in a source of truth, output checks and a clear review workflow are designed in from the first sprint rather than bolted on.

Where natural-language analytics genuinely works

Text-to-SQL is not one problem. Its difficulty depends on three things: how messy the schema is, how ambiguous the business language is, and how costly a wrong answer would be. When all three are favourable, results can be very good. When any one is unfavourable, accuracy drops quickly.

Good fits

  • Exploratory questions by people who can sanity-check the answer. An operations manager who knows roughly how many tickets the team closes each week will notice if the tool says 40,000. These users get value from speed, and their domain knowledge acts as a free review layer.
  • A bounded domain with a small, well-named data model. A single subject area such as support tickets, orders or inventory, exposed through a handful of clearly named views with documented columns.
  • Repeatable question shapes. “Top N by metric over period, filtered by dimension” covers a surprising share of real requests. These are the queries models generate most reliably.
  • Drafting SQL for analysts. Generating a first draft that a person who reads SQL then reviews and edits is a lower-risk, high-value use. The analyst remains accountable for the final query.

Poor fits

  • Raw production schemas with hundreds of tables, legacy naming (tbl_cust2, flag_x) and business rules hidden in application code.
  • Metrics with contested definitions. If finance and sales disagree on what “active customer” means, the model will pick one definition silently.
  • Regulated or externally reported figures where an error has legal or financial consequences.
  • Customer-facing analytics over shared, multi-tenant tables without database-enforced isolation. One faulty WHERE clause becomes a data breach.

What the research says about accuracy

Vendor demos usually quote academic benchmarks, and those benchmarks are much easier than enterprise data. The authors of Spider 2.0, a benchmark built from 632 real enterprise text-to-SQL workflow problems on systems such as BigQuery and Snowflake, report that an o1-preview based agent solved only 21.3% of tasks, compared with 91.2% on the original Spider and 73.0% on BIRD. Their databases often have more than 1,000 columns. Models have improved since, but only your own test set tells you how they perform on your warehouse.

Action: list the ten questions your target users ask most often, and check whether each could be answered from five or fewer clearly named tables or views. If not, the first project is data modelling, not AI.

Architecture options and their trade-offs

There are four common patterns. They differ in flexibility, accuracy and how much damage a wrong generation can do.

PatternHow it worksStrengthsWeaknessesBest for
Raw schema text-to-SQLModel sees table definitions and writes free-form SQL against production or a replicaFast to prototype; answers anything in theoryLowest accuracy; highest blast radius; hidden business rules ignoredInternal demos only
Semantic layer text-to-SQLModel writes SQL only against curated views with documented columns, joins and metric definitionsMuch better accuracy; business rules live in the viewsRequires data modelling effort; new questions may need new viewsMost internal analytics assistants
Metric or query templatesModel maps a question to a pre-approved parameterised query or metric API and fills in parametersHighly predictable; easy to test and secureNarrower coverage; unanswerable questions must be declinedCustomer-facing and regulated use
Analyst copilotModel drafts SQL inside an editor; a person reviews and runs itLarge productivity gain with a human in controlRequires SQL-literate usersData teams and power users

Why the semantic layer matters most

In practice, the single biggest accuracy lever is not the model. It is what the model is allowed to see. A view called v_monthly_net_revenue_by_account with a column comment explaining that refunds and cancelled orders are excluded removes an entire class of errors. The definition of “revenue” now lives in SQL that your data team reviewed once, instead of being re-derived by a model on every question.

If you already have a warehouse or lakehouse, this layer usually sits on top of it. Our guide to choosing a data platform for analytics and AI covers the underlying platform decision; the semantic layer is the part that makes it usable by a language model.

Hybrid is the usual answer

Most production systems we would recommend combine patterns. Common, high-stakes questions such as “revenue this month” go through templates or a metric API, so they always return the same governed number. Long-tail questions fall through to semantic-layer text-to-SQL with clear labelling, and anything else is declined.

Action: decide which pattern each user group gets. Customer-facing users should almost never receive free-form SQL generation.

The safety controls that must live in the database

The most important design principle is simple: assume the generated SQL is wrong or hostile, and make the database refuse anything harmful. Prompts that say “only write SELECT statements” are guidance for the model, not a security control. Prompt injection can arrive through the user’s question or through data the model reads, as we describe in our article on protecting tools, data and actions from prompt injection.

The OWASP Top 10 for LLM Applications (2025) entry on Excessive Agency makes the same point: grant downstream permissions only as needed, such as read-only database access, run actions in the context of the specific user with minimal privileges, and enforce authorisation in downstream systems rather than relying on the model to decide what is allowed.

1. A dedicated, read-only database role

Connect the assistant through a role that has SELECT on the semantic views and nothing else: no access to base tables, no write privileges, no ownership of objects. In PostgreSQL you can additionally set default_transaction_read_only for that role; the PostgreSQL documentation notes that a read-only transaction cannot alter non-temporary tables. Ideally, point the assistant at a read replica so a heavy query cannot slow down production.

2. Row-level security for per-user and per-tenant data

If different users may see different rows, enforce that with database policies, not with a filter the model is asked to add. PostgreSQL’s row security policies are default-deny once enabled: if no policy allows access, no rows are visible. Two details matter. Table owners bypass row security unless you use FORCE ROW LEVEL SECURITY, and superusers and roles with BYPASSRLS always bypass it. The assistant’s role must therefore be neither an owner nor privileged. Set the user or tenant identity in a session variable that the policies read, from your authenticated application session, never from anything the model produces.

3. Resource limits

Generated queries can be accidentally expensive: a missing join condition produces a cartesian product. Set statement_timeout on the assistant’s role or session (PostgreSQL’s documentation advises against setting it globally in postgresql.conf because it would affect all sessions), cap returned rows, and on cloud warehouses use per-query byte or cost limits where the platform supports them.

4. Static checks before execution

  • Parse the SQL with a proper parser, not a regular expression, and reject anything that is not a single SELECT.
  • Check referenced objects against an allow-list of views and columns.
  • Block functions that can reach the file system, network or catalogue metadata.
  • Reject queries without a LIMIT or add one automatically.

5. Logging and review

Log the question, generated SQL, user identity, row count and execution time for every request. These logs are your evaluation dataset, your audit trail and your early warning of misuse.

Action: before any user test, ask a developer to try to make the assistant delete a row, read another tenant’s data and run a ten-minute query. Each attempt should fail at the database, not at the prompt.

Making answers accurate and trustworthy for business users

Security stops the worst outcomes. Accuracy and transparency decide whether people trust and keep using the tool.

Give the model better context, not more context

  • Curated schema descriptions: column comments, allowed values for categorical fields and example rows for ambiguous columns.
  • A business glossary: “active customer”, “churn”, “net revenue” defined once, in plain language, mapped to the view or column that implements each term.
  • Verified example queries: pairs of real questions and approved SQL, retrieved by similarity and shown to the model as patterns.

Show your working

Every answer should display the generated SQL (collapsible for non-technical users), a plain-English restatement of how the question was interpreted (“Interpreted ‘last quarter’ as April to June 2026; excluded cancelled orders”), and the data freshness. Users catch a surprising number of errors themselves when the interpretation is spelled out.

Ask before guessing

When a question is ambiguous (“top customers” by revenue, order count or margin?), the assistant should ask a clarifying question or offer options rather than choosing silently. This costs a few seconds and prevents a large share of confident-but-wrong answers.

Charts and summaries are a second generation step

If the model also writes a narrative summary of the result, that summary can misstate the numbers. Generate narrative text only from the returned rows, check that every figure in the text appears in the result set, and keep the table visible next to the summary. Our article on guardrails for generative AI describes this kind of output check in more detail.

Action: write the interpretation banner and the “show SQL” panel into the first design mock-up. Retrofitting transparency is harder than designing it in.

How to evaluate before launch and after every change

Evaluation is the part teams most often skip, and it is the part that tells you whether the product is ready.

Build a golden question set

  1. Collect 100 to 200 real questions from target users, including messy phrasing and ambiguous ones.
  2. Have an analyst write the correct SQL and record the expected result for each, against a frozen snapshot of the data.
  3. Tag each question by difficulty, subject area and risk (would a wrong answer change a decision?).
  4. Include questions the system should decline, such as requests for data outside scope or for another tenant’s records.

Score what matters

MetricWhat it tells youHow to measure
Execution accuracyDoes the result match the expected answer?Compare result sets, not SQL text; different SQL can be equally correct
Correct refusal rateDoes it decline out-of-scope or unsafe requests?Share of “should decline” questions that were declined
Clarification rateDoes it ask when the question is genuinely ambiguous?Manual review of ambiguous-tagged questions
Latency and costIs it fast and affordable enough?Median and 95th percentile time; model and warehouse cost per question

Set a launch bar per risk level

There is no universal accuracy threshold. A tool for analysts who review every query can launch at a lower bar than a dashboard assistant used by executives. Agree the bar with the business owner before testing, not after you see the numbers. As an illustrative assumption, a team might require near-perfect results on high-risk template questions and accept lower accuracy on exploratory long-tail questions, provided those are clearly labelled.

Re-run on every change

Run the golden set automatically whenever you change the model, the prompt, the glossary or the semantic views. Schema changes break text-to-SQL silently; a renamed column can turn correct answers into wrong ones without any error.

Action: treat the golden set as a product asset with an owner. Add every production error a user reports to it.

A step-by-step rollout plan

For example, a 60-person distribution company wanting sales managers to query order data might proceed like this. The timings are illustrative and depend heavily on data quality.

  1. Scope one subject area. Orders and accounts only. Agree the twenty most common questions and the metric definitions with sales and finance together.
  2. Build the semantic layer. Five to ten views with documented columns, materialised where performance requires it, on a read replica.
  3. Lock down access. Dedicated read-only role, row-level security by region if managers should only see their own territory, timeouts and row caps.
  4. Create templates for the top questions and semantic-layer text-to-SQL for the rest.
  5. Build the golden set and evaluate. Fix failures by improving views and glossary entries before touching prompts.
  6. Pilot with five friendly users who know the numbers well. Review every query log weekly.
  7. Expand gradually by user group and subject area, re-running evaluation at each step.

Where approvals belong

Natural-language analytics should be read-only. If the roadmap includes actions, such as “update the forecast” or “email this list to the team”, those need explicit approval steps and separate permissions. We cover that design in deciding what an agent may do on its own.

Action: name a business owner for metric definitions and a technical owner for the semantic layer before development starts. Without them, the project stalls on disagreements the AI cannot resolve.

Costs, risks and a pre-launch checklist

Risk register

RiskLikelihood without controlsPrimary control
Confident wrong answer used in a decisionHighSemantic layer, interpretation banner, golden set, analyst review for high-stakes figures
User sees data they should notMediumRow-level security tied to authenticated identity; no privileged roles
Data modification or destructive queryLow to mediumRead-only role, read-only transactions, SQL parser allow-list
Runaway query cost or loadMediumTimeouts, row caps, cost limits, read replica
Silent breakage after schema changeHighAutomated evaluation in CI on every change

Pre-launch checklist

  • Assistant connects through a dedicated read-only role with access only to approved views.
  • Row-level security enabled and forced where per-user or per-tenant visibility applies; identity comes from the application session.
  • Statement timeout, row cap and warehouse cost limits configured.
  • SQL parsed and checked against an allow-list before execution.
  • Metric definitions agreed and documented in the semantic layer and glossary.
  • Golden question set built, scored, and wired into CI.
  • Every answer shows interpretation, SQL and data freshness.
  • Ambiguous questions trigger clarification; out-of-scope questions are declined.
  • Query logs retained, reviewed weekly during the pilot and fed back into evaluation.
  • Penetration-style tests for injection, cross-tenant access and expensive queries completed.

Frequently asked questions

Can we point a text-to-SQL tool straight at our production database?

We advise against it. Use a read replica and expose curated views through a dedicated read-only role. Raw production schemas reduce accuracy and increase the damage a faulty query can do.

Is prompt engineering enough to stop the model writing harmful SQL?

No. Prompts guide the model but are not a security boundary. Enforce safety in the database with read-only roles, row-level security, timeouts and a SQL allow-list, so that a harmful query fails even if it is generated.

How accurate will it be on our data?

Nobody can tell you without testing on your own questions. Public benchmarks are much easier than enterprise data, so build a golden set of real questions with known answers and measure execution accuracy before launch.

Should customers be able to query their own data in natural language?

It can work, but use pre-approved query templates or a metric API rather than free-form SQL, enforce tenant isolation in the database, and decline anything the system cannot map confidently.

Sources and methodology

Guidance reflects PoliteTech delivery experience. The external references below informed specific points in this article.

  1. arXiv: Spider 2.0 — Evaluating Language Models on Real-World Enterprise Text-to-SQL Workflows (2024, revised 2025) — accessed 9 November 2026. Benchmark gap between academic and enterprise text-to-SQL tasks (21.3% vs 91.2% and 73.0%) and schema scale.
  2. OWASP Gen AI Security Project: LLM06:2025 Excessive Agency — accessed 9 November 2026. Least privilege, read-only database access, user-context execution and enforcing authorisation downstream.
  3. PostgreSQL Documentation: Row Security Policies — accessed 9 November 2026. Default-deny row-level security and owner, superuser and BYPASSRLS bypass behaviour.
  4. PostgreSQL Documentation: Client Connection Defaults — accessed 9 November 2026. statement_timeout behaviour and recommendation, and default_transaction_read_only.

Want staff to query your data in plain English without risking wrong numbers or leaks?

We can review your data model, recommend the right pattern and build a secured, evaluated natural-language analytics pilot.