Scrivio Interview library
DesignIntermediate7 min read · updated 12 November 2026

Product wants a natural-language-to-SQL feature so business users can query the orders database. Design it so it is safe and useful.

We give the model the schema with descriptions of tables and business terms plus example question and SQL pairs, then treat its SQL as untrusted: we parse and validate it (only SELECT, only known tables) and run it as a read-only role on a replica or warehouse, with statement timeouts, row limits and row-level security for the user's permissions. The user sees both the SQL and the result and can correct it, and every question is logged for evaluation. We measure on real questions with known correct answers, and often find that a curated semantic layer gives better results than raw schemas.

Why this question is asked

Business users always have more questions than the analytics team can answer, and natural-language-to-SQL promises to let them ask the database directly: how many orders did we ship to Germany last month. It is also one of the riskiest LLM features, because the model's output is code that runs against company data. A wrong query gives a confident wrong number; a dangerous query can leak or damage data. Interviewers ask this design question to see whether we can make the feature both useful and safe. In this answer, we will design the prompt with schema and examples, the validation of generated SQL, the restricted execution environment, the user experience, and the evaluation, and see why a semantic layer often beats raw schemas.

1Giving the Model the Right Context

The model can only write good SQL if it knows our schema and what the business means by its words. Table and column names alone are not enough: does revenue mean order total including or excluding tax, and before or after refunds? Is a customer active if they ordered in the last 90 days? So the prompt includes the relevant tables with column types and a one-line description of each table and important column, definitions of common business terms, and a handful of example questions with correct SQL, which teach the model our conventions far better than rules do.

For a large schema we do not send everything. We retrieve the tables and examples most relevant to the question, a small RAG step over schema descriptions, so the prompt stays focused and within budget.

SQL
-- Part of the schema context sent to the model
-- orders: one row per customer order. status in ('NEW','PAID','SHIPPED','CANCELLED','REFUNDED')
-- id bigint, customer_id bigint, country char(2), region text, total_net numeric(12,2), created_at timestamptz, shipped_at timestamptz
-- Business terms: revenue = sum(total_net) for orders with status in ('PAID','SHIPPED'); last month = previous calendar month
-- Example
-- Q: How many orders did we ship to Germany last month?
SELECT count(*) FROM orders
WHERE country = 'DE' AND status = 'SHIPPED'
AND shipped_at >= date_trunc('month', now()) - interval '1 month'
AND shipped_at < date_trunc('month', now());

2Validating the Generated SQL Before It Runs

The SQL the model returns is untrusted input, as if a stranger had typed it. Before anything runs, we parse it with a real SQL parser, such as JSqlParser in Java, and apply rules: exactly one statement, and it must be a SELECT; only tables and views from an allow list; no functions known to be dangerous or expensive, such as functions that read files or sleep. Anything else is rejected with a clear message, and the model can be asked once to try again.

Java
Statement st = CCJSqlParserUtil.parse(generatedSql); // throws on invalid SQL
if (!(st instanceof Select)) {
throw new RejectedQuery("only SELECT queries are allowed"); // DELETE FROM orders -> rejected
}
Set<String> tables = new TablesNamesFinder().getTables(st); // method name varies by JSqlParser version
if (!ALLOWED_TABLES.containsAll(tables)) {
throw new RejectedQuery("unknown table in " + tables); // [orders, pg_shadow] -> rejected
}
// passes: SELECT count(*) FROM orders WHERE country = 'DE' ...

Validation is the first line, not the only one. Parsers and allow lists can be bypassed in clever ways, so the database itself must also make dangerous queries impossible.

3Running It in a Restricted Environment

The execution environment is designed so that even a query that slips through validation cannot do harm. Queries run on a read replica or a data warehouse, never the primary database that the order system writes to, so a heavy query cannot slow down checkout. They connect as a dedicated database role that has SELECT on the allowed tables and views only, and no rights to write or to read anything else. Each query runs in a read-only transaction with a statement timeout, for example 5 seconds, and results are capped, for example 1,000 rows.

Users also have different permissions: a regional manager may only see orders from their region. We enforce that in the database with row-level security, a PostgreSQL feature that adds a filter to every query on a table based on settings of the current session, so generated SQL cannot read other regions even if it does not mention region at all.

SQL
-- Once, by the DBA
CREATE ROLE nl_query NOLOGIN;
GRANT SELECT ON orders, customers_view TO nl_query;
ALTER TABLE orders ENABLE ROW LEVEL SECURITY;
CREATE POLICY by_region ON orders FOR SELECT TO nl_query
USING (region = current_setting('app.region'));
-- Per request, from Java, inside a read-only transaction on the replica
SET LOCAL ROLE nl_query;
SET LOCAL statement_timeout = '5s';
SELECT set_config('app.region', 'EMEA', true); -- from the authenticated user, never from the model
-- then the validated SELECT, wrapped as: SELECT * FROM (<query>) q LIMIT 1000
Step throughFrom question to answer
  1. User asks a questionauthenticated, region known
  2. Retrieve schema descriptions and examples
  3. Model writes SQLlow temperature
  4. Parses as one SELECT on allowed tables?
    YesRun in restricted environmentNoReject, maybe one retry
  5. Replica, read-only role, RLS, timeout, row cap
  6. Show SQL and result, user can correctlog for evaluation

6 steps in order. Play them, or step through them one at a time.

4Showing the SQL and Letting Users Correct It

A number without its query is hard to trust. So the interface shows the result together with the SQL and a plain-language explanation of what it does: counted shipped orders to Germany between 1 and 31 October. Users who know a little SQL can spot mistakes, and everyone can see the interpretation, for instance that last month was taken as the previous calendar month rather than the last 30 days. Users can rephrase, edit the SQL (which goes through the same validation), or mark the answer as wrong.

Every interaction is logged: the question, the generated SQL, whether it was rejected, the user's feedback and corrections. That log is the raw material for evaluation and for new examples in the prompt.

5Evaluating, and Why a Semantic Layer Helps

We measure the feature on a set of real business questions with known correct answers, collected from analysts and from the logs, and score whether the generated SQL returns the right result, not whether it matches a reference query text, since many queries can be correct. Accuracy on that set, broken down by question type, tells us whether a prompt change or a new model helps.

Many teams discover that the hardest part is not SQL syntax but business meaning across a raw, normalised schema with dozens of tables and historical quirks. A curated semantic layer, a small set of well-named views or a metrics layer with defined measures like revenue and dimensions like country and month, makes the model's job much easier: fewer joins to get wrong, business terms already defined, and permissions applied to fewer objects. Querying a clean orders_summary view usually beats querying twelve raw tables.

Raw schema versus semantic layer
AspectRaw tablesCurated semantic layer
Objects the model seesDozens of normalised tablesA few named views or metrics
Business termsMust be inferred from columnsDefined once, e.g. revenue
Typical errorsWrong joins, double countingFewer, mostly filters
PermissionsOn every tableOn a few views, plus RLS
Accuracy on our question setLower (measure it)Usually higher (measure it)

6Follow-up questions

Why not let the model call a fixed set of query APIs instead of writing SQL?

For common questions that is often better: a tool like countOrders(country, status, dateRange) is safe and precise. Many designs combine both, using tools or the semantic layer for frequent questions and generated SQL for the long tail, with the restrictions above.

What if a valid query is extremely expensive?

The statement timeout stops it on the replica, and we can also run EXPLAIN first and reject plans above a cost threshold. Per-user rate limits stop someone running many heavy queries in a row.

How do you prevent the model from seeing sensitive data?

The model only sees the schema description and examples, not the data, unless we ask it to explain results. If results are sent back to the model for a narrative answer, they are subject to the same permissions and data classification rules as any other prompt.

7Conclusion

In this answer, we designed a natural-language-to-SQL feature that is safe and useful. The model gets the schema with business descriptions and example question and SQL pairs. Its SQL is parsed and validated to allow only a SELECT on known tables, then run as a read-only role on a replica with timeouts, row limits and row-level security for the user's permissions. Users see the SQL and the result and can correct it, everything is logged for evaluation on real questions with known answers, and a curated semantic layer usually gives better results than raw schemas.

What to say in the interviewAbout 90 seconds aloud

Open with

I would design it so the model is helpful but never trusted. For usefulness, the prompt includes the relevant tables with descriptions of tables, columns and business terms, like what revenue means and what last month means, plus a few example questions with correct SQL; for a large schema I retrieve only the relevant parts.

Then, if they want more

For safety, I treat the generated SQL as untrusted input. I parse it with a real parser such as JSqlParser and only accept a single SELECT on an allow list of tables.

Then the database makes damage impossible anyway: queries run on a read replica or the warehouse, as a dedicated role with SELECT on allowed views only, in a read-only transaction with a statement timeout and a row limit, and row-level security filters rows by the user's permissions, set from the authenticated user, never from the model.

In the interface I show the result with the SQL and a plain explanation of how the question was interpreted, so users can spot a wrong interpretation, edit or rephrase, and mark answers as wrong. Everything is logged. I evaluate on a set of real questions with known correct results, comparing results rather than query text.

And I would push for a curated semantic layer of well-named views or metrics, because in practice that improves accuracy more than prompt tweaks over a raw schema.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Official documentation
Spring AI reference
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Product wants a natural-language-to-SQL feature so business users can query the orders...": https://scrivio-interview-library.netlify.app/spring-boot/llm-fundamentals/70a24b5f19/