The scary thing about an AI-written SQL query isn't the one that throws an error. It's the one that runs cleanly, returns a tidy table, and is quietly wrong. Revenue that's double what finance reports. A customer count that includes people who never bought anything. You paste it into a dashboard and nobody notices for a month.
My name is Artem and I run the Writingmate blog. I generate SQL with LLMs almost every week, mostly for reporting questions and for untangling queries I inherited. Over time I've settled on one habit: never ask for SQL without handing the model the schema, and never trust the output until it has survived a short check. This guide is that process, from picking the right kind of job to a 4-minute dry-run check you can do before anything touches real data.
If you just want to try a prompt, the free Writingmate AI code generator handles SQL like any other language, and you can paste the template below straight into it.
Why AI SQL fails quietly
A model that writes SQL has never seen your database. It sees your words and whatever you pasted. So when you say "monthly revenue by customer," it guesses which table holds revenue, which column is the date, and whether "customer" means a row in users or accounts. A confident guess looks exactly like a correct answer.
The failure is also hard to catch because SQL is forgiving. A wrong join type, a missing filter or a typo in a string literal won't crash anything. It just changes the numbers.
OWOX published a test of exactly this on October 14, 2026: 36 runs across ChatGPT (free plan) and Claude, six business questions against a BigQuery demo shop warehouse, with the models given only the schema text. In the 24 plain runs, five answers were wrong. All 24 passed the dry run and executed, and none produced a loud error. The causes were mundane: four runs wrote 'completed' where the data had 'Completed', and one used a status value that didn't exist. All five came back empty, NULL or zero. That's one warehouse and a handful of questions, so treat it as an illustration, not a benchmark. But it matches what I see: the dry run proves the query is valid, not that it's right. (OWOX write-up)
Stanford's CS145 course notes on LLM-generated SQL list the same families of mistakes: NULL handling, JOIN cardinality, and mixing up WHERE with HAVING.
"We've achieved state-of-the-art results on the highly competitive BIRD benchmark, translating natural language into execution-ready SQL queries." — Google Research on X
Notice the phrase "execution-ready." Even the labs measure whether a query runs and matches a reference answer on a benchmark database. Your database has your column names, your messy status values and your one-to-many relationships. Benchmarks tell you models are getting better. They don't tell you your query is correct.
Sort the job first
"Write me some SQL" covers very different tasks, and each one fails differently. Here's how I sort them before I write the prompt.
SQL job | Typical failure | What to give the model |
|---|---|---|
Reporting (totals, group by, filters) | Wrong metric definition, wrong date window, typo in a status literal | Schema plus the real distinct values of any column you filter on |
Multi-table joins | Fan-out from one-to-many joins, inflated SUMs, accidental INNER JOIN dropping rows | Keys, relationship direction (one-to-many), and the grain you want |
Window functions | Wrong PARTITION BY, ties handled badly, frame defaults surprise you | Sample rows and the expected output for those rows |
Debugging a broken query | The model "fixes" the error by changing what the query means | The query, the exact error, and the intended result in plain words |
Optimization | A rewrite that's faster but returns different rows | The EXPLAIN output, table sizes and existing indexes |
Two rules fall out of this table. For reporting and joins, the model needs facts about your data, not just your tables. For debugging and optimization, you need a before/after comparison, because the risk is a changed result, not a syntax error.
The prompt that pins dialect, schema and read-only rules
A vague question gets a plausible guess. This template removes the places where the model has to guess. Copy it and fill in the brackets:
You are writing SQL for [PostgreSQL 16 / MySQL 8 / BigQuery / SQL Server / SQLite].
Use only syntax valid in that dialect.
SCHEMA (use only these tables and columns, never invent any):
[paste CREATE TABLE statements, or table(column type, ...) lines]
RELATIONSHIPS:
- orders.customer_id -> customers.id (many orders per customer)
- order_items.order_id -> orders.id (many items per order)
SAMPLE ROWS (3-5 per table, anonymized):
[paste rows]
VALUES YOU MAY FILTER ON:
- orders.status: 'Completed', 'Refunded', 'Pending'
QUESTION:
[plain-English question, including the date range and what one row of the result means]
RULES:
- Read-only. Output a single SELECT (or WITH ... SELECT). No INSERT, UPDATE, DELETE, DROP, ALTER, TRUNCATE or MERGE.
- If the question needs a column or table not listed, say what is missing instead of guessing.
- State the grain of the result (one row per ...) in a comment on the first line.
- Add a LIMIT 100 while I test.
- After the query, list your assumptions in 3 bullets.
Each block earns its place:
- Dialect and version. Date functions, string concatenation, quoting and
LIMITversusTOPall differ. "SQL" isn't a dialect. - Schema with "never invent." This stops made-up columns. Giving the model permission to say "this column is missing" matters just as much.
- Relationships. Join fan-out happens when the model doesn't know that one order has many items. Say it out loud.
- Allowed values. That's the OWOX lesson. If the data says
'Completed', tell the model. - Grain statement. Forcing "one row per customer per month" in a comment gives you something concrete to verify later.
- Read-only rule. It doesn't make the model incapable of writing a DELETE, so it's a request, not a guarantee. The real protection is a read-only database user, covered below.
Don't paste real customer data as sample rows. Invent a few lookalike rows or mask names and emails. The model needs the shape of the data, not the people in it.
The 4-minute dry-run check
Do this on a staging copy, a read replica or a read-only database user. Never run first-draft generated SQL on a primary database with write access.
Minute 1: Read for write statements and wide scans
Search the query for INSERT, UPDATE, DELETE, DROP, ALTER, TRUNCATE, MERGE and CREATE. Check for multiple statements separated by semicolons. Then read it once in plain English: does the grain on line one match the question? Does the date window match? Are the status literals ones you gave it?
Minute 2: Run EXPLAIN
Run EXPLAIN (or your engine's equivalent) before executing. In PostgreSQL, plain EXPLAIN shows the plan without running the query, while EXPLAIN ANALYZE actually executes it, so don't use ANALYZE on anything with side effects. You're looking for full table scans on large tables, a join with no join condition (a cartesian product), and wildly off row estimates. In BigQuery the equivalent is a dry run that shows bytes processed.
Remember what EXPLAIN can't tell you: whether the answer is right. That's why the next two steps exist.
Minute 3: Test on a limited sample
Run it with LIMIT 20 or restrict to one customer, one day or one account whose numbers you can verify by hand. Pick a case where you already know the answer. If the query says customer 1042 spent 310 and you know their orders add up to 180, you've found the bug in thirty seconds.
Minute 4: Row counts and join fan-out
This step caught the most problems in the OWOX test: counting rows after each filter and join to find where they drop to zero or multiply, and reconciling one total against a number computed from the raw table. Do both:
- Reconcile one total. Compute the same total with a dead-simple query (
SELECT SUM(amount) FROM orders WHERE status = 'Completed') and compare. If the fancy query returns more, a join is multiplying rows. - Count at each step. Run
SELECT COUNT(*)on the base table, then after adding each join. If a join toorder_itemstakes 1,000 orders to 3,400 rows and you thenSUM(orders.total), every order total is counted once per line item. - Check key uniqueness. If the result should be one row per customer, run
SELECT customer_id, COUNT(*) ... GROUP BY 1 HAVING COUNT(*) > 1on the output. Any rows back means the grain is broken. - Check NULLs. Count NULLs in the key columns. An INNER JOIN silently drops unmatched rows, and a LEFT JOIN with a WHERE on the right table quietly turns back into an INNER JOIN.
One caveat from the same OWOX test: a simple row count against an expected number of entities caught none of the five wrong answers. Count rows between steps, not just at the end.
Safety: don't rely on the prompt alone
"Read-only" in a prompt is an instruction, and models occasionally ignore instructions. Two controls actually enforce it:
- Run generated SQL as a read-only database user with SELECT-only grants, ideally on a replica. If a stray DELETE slips through, it fails with a permissions error.
- Wrap anything that writes in a transaction you roll back first. If you do need an UPDATE, ask for the matching SELECT that shows exactly which rows it would touch, and run that first.
I treat AI SQL the same way I treat any code I didn't write. I covered the general version of that habit in the 5-minute check before you run generated code; SQL just adds the data-specific traps above.
Compare several models on the same query
Here's where I've found real value in using more than one model. A single model gives you one confident answer. Two or three models give you a way to spot disagreement, and disagreement is where the bugs hide.
How I compare, in four steps:
- Paste the same filled-in template into several models in one Writingmate chat (the platform has 200+ models available, so you can pick a mix of fast and strong ones).
- Check whether they chose the same join type and the same grain.
- Run each on the limited sample and compare the outputs row by row.
- Where results differ, ask one model to explain the difference. That usually points straight at a fan-out, a NULL case or an assumption you never specified.
Agreement isn't proof, since models can share the same wrong guess. But disagreement is a free warning, and it costs you one extra paste. The same trick works as a "second opinion" when you ask one model to review another's query for fan-out and filter mistakes.
Signal | What it means | What to do |
|---|---|---|
All models pick the same joins and grain | Your prompt is probably clear | Still run the 4-minute check |
Models pick different join types | Relationship or grain is ambiguous | Add the missing relationship to the prompt |
Totals differ by a clean multiple | Likely join fan-out in one of them | Count rows after each join |
One query returns zero rows | Likely a wrong literal or filter | Check distinct values of the filtered column |
If you're deciding where to run this regularly, the Writingmate pricing page lists what each plan includes. For one-off queries, the free code generator is plenty.
Free tool or full chat: which to use
A free generator is fine for syntax help, a quick GROUP BY, or learning how window functions work. It starts to hurt when you need to iterate: pasting a schema once and asking five follow-up questions, or comparing models. That's a chat workflow, where your schema stays in context and you can say "now add a filter for last quarter" without re-pasting.
If you're sorting through your options more broadly, the Reddit thread titled "ChatGPT cannot be trusted" in r/arduino is a good reminder of how this goes in any code domain: it sounds sure, and it isn't always right. SQL has the extra twist that the wrong answer looks like real data.
My short version
So here's the bottom line. Tell the model your dialect, your tables, your relationships and the exact values it may filter on. Make it state the grain. Run the result as a read-only user, then spend four minutes on the check: scan for writes, run EXPLAIN, test a sample you can verify by hand, and count rows after every join. If two models disagree, treat that as the most useful thing the exercise produced.
Try the template in the free AI code generator on a query you already know the answer to. That's the safest way to learn how much to trust it.
See you in the next one!
Artem
Frequently Asked Questions
Sources
Written by
Artem Vysotsky
Ex-Staff Engineer at Meta. Building the technical foundation to make AI accessible to everyone.
Reviewed by
Sergey Vysotsky
Ex-Chief Editor / PM at Mosaic. Passionate about making AI accessible and affordable for everyone.