Skip to content
mentoor

Topic 1 of 4 · 4 min read

Text-to-SQL for questions over tables

Goal: Write a schema description and guardrails for a text-to-SQL tool and catch a generated query that answers the wrong question.

Text-to-SQL lets a model turn a question into a query, but the model only sees what you describe, so the schema description and the database permissions do most of the work. The model does not retrieve rows. It writes code, your database runs it, and the result becomes the context for the answer.

Check yourself · 1 of 3

A text-to-SQL tool must never change data. Where should that rule be enforced?

Choose one answer

Why it matters

Questions like "how many orders shipped late in March?" cannot be answered from text chunks. The answer is a count over a table, and a vector search over exported rows will return a few similar rows and a confident guess. A query returns the exact number.

How to do it

  1. Describe the schema for a reader who has never seen it. Give table names, column names, types, one-line meanings, join keys, and the allowed values of status columns. Two or three sample rows help more than prose. Skip tables the tool should not touch.
  2. Make the database enforce safety, not the prompt. Connect with a role that has SELECT on a short list of tables, run inside a read-only transaction, set a statement timeout, and add a LIMIT when the model forgets one. "Never write DELETE" in a prompt is a request. A missing privilege is a rule.
  3. Show the query with the answer. Return the SQL, the row count and the result so a human or a check step can see what was actually asked.
  4. Check the result against the question. Is the date range right? Did a join duplicate rows? Is a null treated as zero? A query can run cleanly and answer a different question.
  5. Retry with the error. If the database rejects the query, pass the error message back once or twice, then give up with a clear message.

Before and after

Weak tool setup:

You are a SQL expert. Write a query for the user's question. Database: shop.

Fixed setup:

Tables you may query (read-only, PostgreSQL):
orders(id, customer_id, status, total_cents, created_at, shipped_at)
  status is one of: 'new', 'paid', 'shipped', 'refunded'
  total_cents is an integer in cents; created_at is UTC.
customers(id, country, signup_at)
Join: orders.customer_id = customers.id
Rules: SELECT only. Always filter on a date range. Return at most 100 rows.

With the first version the model guesses column names and invents order_total. With the second it knows the money is in cents and which statuses exist.

What goes wrong

  • Plausible wrong columns. The model picks created_at when "shipped" meant shipped_at. The query runs and the number is wrong.
  • Silent fan-out. A join to a table with many rows per order multiplies the sum. Compare the count with a plain count of orders.
  • Prompt-only safety. A user asks the model to "clean up old rows" and the connection can write. Use a read-only role.
  • Giant results. Without a limit, the tool pulls a million rows into the context. Cap rows and aggregate in SQL.

Public benchmarks such as BIRD and Spider 2.0 exist because real schemas are large and messy, and models still miss often on them. Treat every generated query as a draft that needs a check.

Examples

The wrong date column

SELECT count(*) FROM orders
WHERE status = 'shipped'
  AND created_at >= '2026-03-01' AND created_at < '2026-04-01';

The question was "how many orders shipped in March?". The model filtered on created_at, so it counted orders placed in March that are now shipped. The fix is a schema note saying shipped_at is the shipping time, and a check step that restates the question in words next to the SQL.

A join that doubles revenue

A user asks for total revenue per country. The query joins orders to order_items and sums orders.total_cents. An order with three items is counted three times. The check: compare count(DISTINCT orders.id) with the plain order count, or sum order_items.price_cents instead.

Key points

  • The model writes the query and the database runs it, so retrieval here means executing code, not searching text.
  • A schema description needs meanings, join keys, units and the allowed values of status columns, not just table names.
  • Enforce safety in the database with a read-only role, a read-only transaction, a timeout and a row limit; a prompt rule is not a guardrail.
  • Return the SQL and the result with the answer so someone can check what was asked.
  • A query that runs without error can still answer a different question, so check date ranges, joins and nulls.

Common mistakes

  • Describing the schema as a bare list of table names and expecting the model to infer meaning.
  • Relying on a prompt line such as "never modify data" while the connection still has write permission.
  • Returning only the final number without the SQL, so nobody can spot a wrong filter.
  • Letting the query run without a row limit or timeout, which can flood the context or lock a busy database.

Check yourself · 2 of 3

A model writes a valid query that sums orders.total_cents after joining order_items, and revenue looks three times too high. What is the likely cause?

Choose one answer

Check yourself · 3 of 3

Which schema note helps a model most when users ask about money?

Choose one answer

Practice items, not counted towards your mastery.

Start here

More for this topic