To get correct SQL from a plain-English request, give the AI model three things it cannot guess: your schema (tables, columns, types and keys), your SQL dialect, and an exact definition of every business term in the question, such as what “revenue” or “last month” means. Then ask for the query with comments and a plain-English explanation, and verify it on safe data before it touches production. The prompts below follow that order and include a worked example you can adapt.
Text-to-SQL means turning a natural-language question into a runnable SQL query. Models are good at SQL syntax. They fail mostly on context: which of your three status columns matters, whether refunds count, how your tables join. Nearly every fix in this guide is about supplying that context up front.
Why a vague request produces a confident wrong query
A request like “Show me last month’s top customers by revenue” looks clear to a person who knows the database and is ambiguous to everyone else. Without a schema, the model invents plausible table names like customers and orders, picks a column called amount that may not exist, and chooses its own meaning for “last month” and “revenue”. The query often runs, which is the dangerous part, because a query that runs and returns numbers gets trusted.
Count the decisions hidden in that one sentence:
- “Last month”: the previous calendar month, or the last 30 days? In which time zone?
- “Revenue”: gross order value, or net of discounts, refunds and tax? Do cancelled orders count?
- “Top”: top 10, top 5%, or everyone above a threshold? What happens with ties?
- “Customers”: accounts, people, or companies? Are test accounts excluded?
The model will answer every one of those questions silently. Your prompt’s job is to answer them first.
Prompt 1: The reusable schema context block
A schema context block is a short, fixed description of the tables you query most, written once and pasted into every SQL prompt (or saved in a system prompt or project instructions). It is the highest-value piece of the whole workflow. Keep it to the tables that matter, not a full database dump.
The example below describes an illustrative e-commerce database; replace it with your own tables.
<database>
Dialect: PostgreSQL 16. Timestamps are stored in UTC (timestamptz).
Business time zone: America/Sao_Paulo.
Tables:
customers(id bigint PK, email text, created_at timestamptz, is_test boolean)
orders(id bigint PK, customer_id bigint FK -> customers.id, status text, created_at timestamptz)
status values: 'pending', 'paid', 'shipped', 'cancelled', 'refunded'
order_items(id bigint PK, order_id bigint FK -> orders.id, product_id bigint, quantity int, unit_price numeric(10,2), discount numeric(10,2))
One order has many order_items. There is no total column on orders.
Business definitions:
- Revenue = SUM(quantity * unit_price - discount) over order_items
for orders with status IN ('paid', 'shipped').
- Exclude customers where is_test = true from every report.
- "Last month" = the previous calendar month in the business time zone.
</database>
Why each part is there:
- Dialect and version decide syntax:
LIMITin PostgreSQL and MySQL,TOPorOFFSET ... FETCHin SQL Server,DATE_TRUNCin PostgreSQL versus different date functions elsewhere. - Types and keys tell the model how tables join and whether a comparison needs a cast.
- Enumerated status values stop the model from filtering on
status = 'completed'when that value does not exist. - “There is no total column” blocks the most likely hallucination for this schema.
- Business definitions turn ambiguous words into rules, which is where most wrong numbers come from.
- The
<database>tags separate reference material from the request. Our guide to delimiter prompting explains why that separation helps.
If you are not sure how to produce this block, you can generate the raw part from the database itself. In PostgreSQL, pg_dump --schema-only or a query against information_schema.columns lists tables and types; trim the result to the relevant tables and add the business definitions by hand. The business definitions are the part only you can write.
Prompt 2: The query request
The query request combines the schema block with a precise question and rules for the output. Asking the model to list its assumptions before writing SQL is the single most useful line here, because it surfaces wrong interpretations in plain English, where they are easy to spot.
[paste the <database> block]
Task: Write a query that returns the top 10 customers by revenue for last month.
Output columns: customer_id, email, order_count, revenue.
Order by revenue descending. If two customers tie, order by customer_id.
Rules:
- Use only tables and columns listed in <database>. If something you need is missing, stop and say what is missing instead of inventing it.
- Before the query, list every assumption you made, one per line.
- Comment each CTE or major clause with one line explaining what it does.
- Read-only: SELECT statements only.
- Avoid join fan-out: aggregate order_items per order before joining anything else that is one-to-many.
The “stop and say what is missing” rule gives the model a sanctioned alternative to guessing, a pattern we cover in more depth in reducing AI hallucinations with better prompts. The fan-out rule targets the most common silent error in reporting queries, explained below.
What a good answer looks like
For the illustrative schema, a correct response should state its assumptions (for example, that “last month” is computed from the current date in the business time zone) and produce something close to this:
WITH bounds AS (
-- Previous calendar month in the business time zone, converted back to UTC instants
SELECT
(date_trunc('month', now() AT TIME ZONE 'America/Sao_Paulo') - interval '1 month')
AT TIME ZONE 'America/Sao_Paulo' AS start_ts,
date_trunc('month', now() AT TIME ZONE 'America/Sao_Paulo')
AT TIME ZONE 'America/Sao_Paulo' AS end_ts
),
order_revenue AS (
-- One row per qualifying order with its net revenue
SELECT o.id, o.customer_id,
SUM(oi.quantity * oi.unit_price - oi.discount) AS revenue
FROM orders o
JOIN order_items oi ON oi.order_id = o.id
CROSS JOIN bounds b
WHERE o.status IN ('paid', 'shipped')
AND o.created_at >= b.start_ts
AND o.created_at < b.end_ts
GROUP BY o.id, o.customer_id
)
SELECT c.id AS customer_id, c.email,
COUNT(*) AS order_count,
SUM(r.revenue) AS revenue
FROM order_revenue r
JOIN customers c ON c.id = r.customer_id
WHERE c.is_test = false
GROUP BY c.id, c.email
ORDER BY revenue DESC, customer_id
LIMIT 10;
Notice the details a vague prompt would miss: a half-open date range (>= start and < end) instead of BETWEEN, revenue aggregated per order before counting orders, and test accounts excluded. Treat this as an example of the shape to expect, and still run it against your data before relying on it.
Prompt 3: Break complex questions into steps
Complex analytical questions are easier to get right when you specify the plan and let the model write the SQL for each step. Spell out which tables join on which keys, what the grain of each intermediate result is (one row per what), the grouping columns, the aggregates and the filters.
[paste the <database> block]
Question: For each month in 2026, what share of revenue came from customers
whose first paid order was in that same month (new) versus earlier (returning)?
Build it in steps, each as a CTE:
1. first_order: one row per customer with the created_at of their first order
with status IN ('paid','shipped').
2. order_revenue: one row per qualifying order with net revenue (see definition).
3. labeled: order_revenue joined to first_order; label each order 'new' if the
order month equals the first-order month, otherwise 'returning'.
4. Final: one row per month and label, with revenue and share of that month's total.
State the grain of every CTE in its comment. Months in the business time zone.
Stating the grain in each comment is a cheap way to catch structural mistakes. If a CTE that should be “one row per customer” can return several rows for the same customer, the comment and the code will disagree, and a reviewer will notice.
Prompt 4: Make the model explain and attack its own query
A second pass that explains the query in plain English and lists ways it could be wrong catches many errors before you run anything. Use a fresh message so the review is not just the model defending its first answer.
[paste the <database> block]
Here is a query and the question it is meant to answer.
<question>...</question>
<query>...</query>
1. Explain in plain English, clause by clause, what this query returns.
2. Compare that to the question. List any mismatch.
3. Check specifically for: join fan-out that inflates SUM or COUNT; NULL handling
(NOT IN with NULLs, COUNT(column) vs COUNT(*), NULL in arithmetic);
date boundary errors; integer division; missing filters from the business definitions.
4. Propose two small test cases (a few rows per table) that would expose each problem
you found, with the expected output.
The test-case request in step 4 pairs well with our prompts for generating realistic test data and fixtures, which you can use to build a small seed database for checking report queries.
The errors AI-generated SQL makes most often
Most wrong AI-generated queries fail in a small set of predictable ways, and knowing them makes review fast. The table lists each one with how to spot it and the prompt rule that prevents it.
| Error | How to spot it | Prompt rule that prevents it |
|---|---|---|
| Invented table or column | Query fails, or worse, matches a similarly named column | “Use only tables and columns listed; say what is missing” |
| Join fan-out | Totals larger than expected; COUNT of orders equals COUNT of items | “Aggregate the many side before joining”; state grain per CTE |
| Date boundary off by one | BETWEEN '2026-09-01' AND '2026-09-30' on a timestamp drops most of the last day | “Use half-open ranges: >= start and < next period start” |
| Time zone ignored | Month totals shift slightly compared with another report | Business time zone stated in the schema block |
NOT IN with NULLs | Query unexpectedly returns zero rows | “Prefer NOT EXISTS over NOT IN for subqueries” |
| Integer division | Ratios come back as 0 or 1 | “Cast to numeric before dividing” |
| Wrong dialect function | Syntax error, or a function that exists with different behavior | Dialect and version on the first line of the schema block |
| Missing business filter | Test accounts or cancelled orders appear in results | Business definitions in the schema block |
Running generated SQL safely
Generated SQL should be treated like code from a new team member: reviewed before it runs, and run with limited permissions. The safety controls belong in the database and in your application, not in the prompt, because a prompt can be ignored or manipulated.
- Use a read-only role. Connect with a database user that has
SELECTonly on the tables needed. In PostgreSQL you can also make sessions read-only by default withdefault_transaction_read_only; the PostgreSQL client configuration docs describe it as the default read-only status of each new transaction. - Set a timeout. PostgreSQL’s
statement_timeoutaborts any statement that runs longer than the limit, which protects you from an accidental cross join on a large table. - Run on a replica or staging copy first, or add a
LIMITwhile exploring. - Check row counts against something you know. If last month had roughly 4,000 paid orders in your dashboard, a query reporting 11,000 has a fan-out problem.
- Never auto-run writes. For
UPDATE,DELETEor schema changes, run aSELECTwith the sameWHEREclause first, wrap the change in a transaction, and review the affected row count before committing. For schema changes specifically, see our prompts for writing safer database migration scripts.
If you are building a text-to-SQL feature for users
Letting end users type questions that become SQL adds a security problem on top of the accuracy problem. The OWASP Top 10 for LLM Applications entry on improper output handling uses exactly this scenario as an example: a user asks a chat feature to run a query that deletes tables, and the application executes it without scrutiny. OWASP recommends treating the model like any other user, with zero trust, validating its output before it reaches backend functions, and using parameterized queries for database operations that involve model output.
In practice that means a read-only connection scoped to an allowlist of tables or views, a parser check that rejects anything other than a single SELECT, row and time limits, and logging of every generated query. Text pasted into the question box can also contain instructions aimed at the model, which is covered in our guide to prompt injection and how to defend against it.
Prompt 5: Speed up a slow query with the execution plan
Performance tuning works far better when the model sees the actual execution plan instead of guessing from the query text. Run EXPLAIN (ANALYZE, BUFFERS) in PostgreSQL (or your engine’s equivalent) on a non-production copy and paste the output.
[paste the <database> block, including existing indexes]
This query is slow. Here is the query and its EXPLAIN (ANALYZE, BUFFERS) output.
<query>...</query>
<plan>...</plan>
1. Identify the node that accounts for most of the time and explain why, citing the plan.
2. Suggest at most three changes, ranked by expected impact: query rewrite, index, or statistics.
3. For each index you suggest, give the CREATE INDEX statement and the write-cost trade-off.
4. Do not change what the query returns. If a rewrite might change results, say so.
Requiring the model to cite the plan keeps the advice tied to evidence instead of generic tips like “add an index on every foreign key”. The last rule protects correctness, which matters more than speed.
Getting consistent results across sessions
Inconsistent answers to the same question usually mean the prompt left room for interpretation. Three habits reduce it:
- Version the schema block. Keep it in your repository next to the migrations and update it when tables change, so every prompt uses the same definitions.
- Save verified queries as examples. When a query has been checked, add it with its question to a small library. Including one or two related examples in a new prompt teaches the model your conventions.
- Ask for assumptions every time. Comparing assumption lists between two runs shows you exactly where the question is ambiguous.



