Most companies run on their ERP, yet most people in those companies can't get answers out of it without waiting for a report. Natural-language-to-SQL (often called NL-to-SQL or text-to-SQL) changes that: a user types "Which suppliers had the highest spend this quarter?" and gets a table, a chart, and the query that produced it.
It sounds simple. On real ERP data, it isn't. This article explains why, and walks through the architecture we use to make NL-to-SQL accurate and safe enough for business use.
Why ERP data is hard for text-to-SQL
Public demos of text-to-SQL usually run on small, tidy databases. ERP systems are neither small nor tidy:
- Scale. An ERP can contain hundreds or thousands of tables. No language model can usefully read all of them in one prompt.
- Cryptic names. Columns like
KUNNR,po_hdr_amt_lc, orflag_3mean nothing without documentation. - Business definitions. "Revenue", "active customer", or "on-time delivery" are defined by the business, not by the schema. Two departments may define them differently.
- Time logic. Fiscal years, accounting periods, and "this quarter" rarely match calendar dates.
- Joins with traps. Header and line-item tables, soft-deleted rows, currency conversions, and status codes all change the right answer.
- Access control. Not everyone may see salaries, margins, or another region's data.
A model that writes syntactically valid SQL can still return a confidently wrong number. The architecture has to prevent that.
An architecture that works
A reliable NL-to-SQL system is a pipeline, not a single prompt. Each stage narrows the problem and catches a different kind of mistake.
- Build a semantic layer. Select the tables that matter for analytics and describe them in plain language: what each table holds, what key columns mean, how tables join, and how core metrics are calculated. This curated layer is the most valuable part of the whole system.
- Retrieve only the relevant schema. For each question, retrieve the few tables, columns, and metric definitions that are likely to be needed—plus a handful of similar example questions with known-good SQL. This is retrieval-augmented generation applied to your schema.
- Generate with constraints. Ask the model for one query in your SQL dialect, using only the retrieved tables, with explicit date and currency rules. Ask it to state its assumptions.
- Validate before execution. Parse the SQL, confirm it is a single read-only query, check every table and column against the approved list, and add a row limit. Reject anything else.
- Execute safely. Run on a read replica or warehouse with a read-only role, a statement timeout, and row-level security for the user who asked.
- Explain the answer. Show the result as a table or chart, alongside the SQL and a plain-English summary of what was calculated. Users trust what they can inspect.
- Learn from feedback. Let users flag wrong answers. Reviewed corrections become new examples for retrieval, so the system improves on your actual questions.
Validating generated SQL
Validation is the step teams most often skip, and the one that matters most. The model's output is untrusted input, exactly like text typed into a form.
Here is a compact validator in Python using the open-source sqlglot parser. It allows a single read-only query over approved tables and enforces a row limit:
import sqlglot
from sqlglot import exp
WRITE_NODES = (exp.Insert, exp.Update, exp.Delete, exp.Drop, exp.Create, exp.Alter, exp.Merge, exp.Command)
def validate_readonly(sql: str, allowed_tables: set[str], max_rows: int = 1000) -> str:
"""Reject anything that is not a single read-only query over approved tables."""
statements = sqlglot.parse(sql, read="postgres")
if len(statements) != 1 or statements[0] is None:
raise ValueError("Exactly one SQL statement is allowed")
tree = statements[0]
if not isinstance(tree, exp.Query) or any(tree.find_all(*WRITE_NODES)):
raise ValueError("Only read-only SELECT queries are allowed")
cte_names = {cte.alias_or_name.lower() for cte in tree.find_all(exp.CTE)}
tables = {t.name.lower() for t in tree.find_all(exp.Table)} - cte_names
unknown = tables - allowed_tables
if unknown:
raise ValueError(f"Query uses tables outside the approved set: {sorted(unknown)}")
if not tree.args.get("limit"):
tree = tree.limit(max_rows)
return tree.sql(dialect="postgres")
This blocks DELETE and UPDATE statements, stacked statements such as SELECT …; DROP TABLE …, and queries against tables the user shouldn't reach—while still allowing common analytics patterns such as joins, CTEs, and unions.
Validation in code is a second line of defence, not the first. The database role that executes the query must itself be read-only and limited to approved views.
Security guardrails
Treat NL-to-SQL like any system that runs queries on behalf of users:
- Least privilege. A dedicated read-only database role, scoped to curated views rather than raw tables.
- Row-level security. Enforce what each user may see in the database, not in the prompt. Prompts can be talked around; database policies can't.
- Sensitive data. Exclude or mask personal and confidential fields from the semantic layer entirely.
- Resource limits. Statement timeouts, row limits, and query cost checks protect production systems from runaway queries.
- Audit trail. Log the question, the user, the generated SQL, and the result size for every request.
Measuring accuracy
"It seems to work" is not an evaluation. Build a test set of real questions your users ask, each with a verified correct answer, and measure the system against it whenever you change prompts, models, or the semantic layer.
Compare results, not SQL strings: two different queries can both be correct, and a query that looks right can be wrong. Track:
| Measure | What it tells you |
|---|---|
| Execution accuracy | Share of questions whose result matches the verified answer |
| Validation rejection rate | How often generated SQL fails safety or schema checks |
| Clarification rate | How often the system asks a follow-up instead of guessing |
| Latency and cost | Time and model cost per answered question |
The most common failure modes are predictable: the wrong join path, the wrong date filter, and an ambiguous metric. The best fix for ambiguity is behavioural—teach the system to ask "Do you mean invoiced revenue or booked revenue?" rather than guess.
When NL-to-SQL is the right tool
NL-to-SQL is strongest for exploratory, ad-hoc questions: the long tail of "what about…" that no dashboard anticipates. It complements dashboards rather than replacing them. Metrics that leadership reviews every week still belong in a governed dashboard with fixed definitions.
A good rollout starts narrow—one domain such as procurement or sales, a well-described set of tables, and a small group of users—then expands as the test set and semantic layer grow.
Getting started
The quality of an NL-to-SQL system depends far more on the semantic layer, validation, and evaluation than on the choice of language model. Start with those foundations and the model becomes the easy part.
SYNYX AI designs and builds natural-language analytics over ERP and database systems as part of our AI solutions work. If you're exploring it for your business, tell us about your data.