How to review AI-written SQL before you trust it

Read AI-written SQL before it runs, then check numbers, not wording. Count the rows of the base table before and after each join: more rows means a fan-out, fewer means lost rows. Run it under a read-only login on a sample, and reconcile one total you already trust. A second reviewer agent is an opinion, not proof.

Get the project

Data scientists · ·

The problem

An assistant writes a query that runs without errors and returns a plausible number. The number is wrong, and nothing tells you. The usual causes are small: a join that multiplies rows, a filter that drops NULLs, an upper date bound that loses the last day. This Pattern is for data engineers and analysts who paste generated SQL into a warehouse and want a short routine that finds these problems from numbers, not from reading style.

Steps

Four checks in order: read the text, run it safely, count rows, reconcile one trusted total.

Four checks, in this order. A fan-out join looks fine in the text and only shows in the row count.

The examples use two tables. orders has three orders of 100, 150 and 100. payments has four rows: order 1 was paid in two instalments of 60 and 40. The total you can verify by hand is 350.

  1. Look for writes before anything else. Generated SQL can contain INSERT, UPDATE, DELETE, MERGE, DROP or TRUNCATE. Flag them in the text, and run anything you are unsure about through a connection that cannot write. In the project, a DELETE sent through a read-only connection failed and the table kept its 2 rows.

    con = duckdb.connect(db_path, read_only=True)   # a write raises an error instead of happening
    
  2. Read every join: what is the key, and is it unique on both sides? A join to a table with several rows per key repeats the rows of the other table. This query looks right and returns 450:

    SELECT sum(o.amount)
    FROM orders o JOIN payments p ON p.order_id = o.order_id;     -- 450, trusted value is 350
    

    Aggregate the many side first, then join. This returns 350:

    SELECT sum(o.amount)
    FROM orders o
    JOIN (SELECT order_id, sum(paid) AS paid FROM payments GROUP BY order_id) p
      ON p.order_id = o.order_id;                                  -- 350
    

    A join with no ON at all is the extreme case. FROM orders o, payments p returned 12 rows, 3 times 4, where the correct join returns 4.

  3. Count rows before and after the join. For a lookup-style join the two numbers must match. This is the only check that catches the fan-out above: the project’s static check finds nothing in that query text.

    SELECT (SELECT count(*) FROM orders) AS base_rows,
           (SELECT count(*) FROM orders o JOIN payments p ON p.order_id = o.order_id) AS joined_rows;
    -- base_rows 3, joined_rows 4: a fan-out
    

    The same guard catches the opposite error. An INNER JOIN to a table that lacks a match for one order returned 3 orders where 4 exist. A LEFT JOIN returned 4. Microsoft’s performance guidance says to filter before joining to reduce the dataset early; the row count tells you whether the join itself is correct.

  4. Reconcile one total you already trust. Pick a number you can check outside the query: a figure from a finance report, or a sum you can do by hand on a sample. The fixed query must reproduce it. In the project, every case compares the bad query, the fixed query and a trusted value.

  5. Read the filters. Two traps are common.

    <> drops NULL. With statuses paid, paid, cancelled and NULL, status <> 'cancelled' counted 2 and status IS DISTINCT FROM 'cancelled' counted 3.

    BETWEEN includes both ends, and a bare date means midnight. With four events (1 Nov 00:00, 15 Nov 12:00, 30 Nov 00:00 and 30 Nov 16:45), BETWEEN '2026-11-01' AND '2026-11-30' counted 3. A half-open range counted all 4:

    WHERE created_at >= '2026-11-01' AND created_at < '2026-12-01'
    
  6. Distrust DISTINCT, CAST in a join key and SELECT *.

    DISTINCT hides a fan-out and keeps the total wrong. sum(DISTINCT o.amount) returned 250, because orders 1 and 3 both have an amount of 100 and collapse into one.

    A CAST in a join key can make different values match. Two coupon codes, '007' and '7', are different codes. ON CAST(r.coupon AS INTEGER) = CAST(c.code AS INTEGER) joined 3 redemptions into 5 rows. Microsoft’s guidance for Fabric Warehouse is to keep matching data types on the columns you join and compare, and to avoid explicit conversions. The project only shows the correctness side of this, not any speed effect.

    SELECT * after a join returned 8 columns where the report needed 3. Microsoft’s guidance says SELECT * can be costly in Fabric Warehouse. Name the columns.

  7. Afterwards, look at what ran in Fabric Warehouse. Adapted from the query insights examples in Microsoft’s documentation. queryinsights.exec_requests_history lists completed queries with statement_type, row_count, allocated_cpu_time_ms and the query text. Queries can take up to 15 minutes to appear, and the history covers 30 days.

    -- Run it in your own warehouse.
    SELECT TOP 20 start_time, statement_type, row_count, allocated_cpu_time_ms, command
    FROM queryinsights.exec_requests_history
    WHERE start_time >= DATEADD(MINUTE, -30, GETUTCDATE())
      AND login_name = USER_NAME()
    ORDER BY allocated_cpu_time_ms DESC;
    

    allocated_cpu_time_ms is allocated CPU time, not capacity units. According to Microsoft’s consumption page, the Capacity Metrics app is the primary tool for when consumption happened and how much was reported, and query insights shows what was running at that time. Use both together if a period looks expensive.

The project

Get the project

sql-review-checklist is a small Python and DuckDB project with synthetic data. It holds eight bad-SQL cases, each with the fixed query and a trusted value, static checks that read SQL text without running it, the row-count guard from step 3, a read-only runner for step 1, and 33 tests.

python -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt
python review.py && python -m pytest -v

What the recorded run showed (full output in RUN_LOG.txt inside the project):

Case Bad query Fixed query Caught by
Fan-out, then SUM 450 350 row-count guard (3 rows became 4)
Missing join condition 12 rows 4 rows static check
SUM(DISTINCT ...) 250 350 static check
INNER JOIN drops rows 3 4 row-count guard (4 rows became 3)
<> and NULL 2 3 static check
BETWEEN on a timestamp 3 4 static check
CAST in a join key 5 3 static check, row-count guard
SELECT * after a join 8 columns 3 static check

python review.py my_query.sql runs only the static checks on a file of your own. The file is read and never executed.

Terminal output of the project: cases 1 and 2, a blocked DELETE and the test summary.

Real output of python review.py (cases 1, 2 and 9) and the test summary, DuckDB 2.0.1, 2026-11-29.

Copy this prompt

When a generated SQL query needs a second pair of eyes, paste it and this prompt into your assistant’s chat. Add a reference total you have already checked. Ask for potential errors, a corrected draft and two checking queries you can run yourself on a sample.

Review this SQL as if you were paying for the compute. Do not run it.

<paste the SQL>

List:
1. Any statement that writes or changes objects.
2. Every join: its key, whether the key is unique on each side,
   and whether the join can multiply or drop rows.
3. Filters that drop NULL, and date ranges that can lose the last day.
4. Any SELECT *, DISTINCT or CAST in a join key.
5. A query that counts the rows of the base table and of the joined result.
6. A query that reconciles <a total I trust> with the result.
Then give a corrected version of the SQL.

Run queries 5 and 6 yourself on a sample. The reviewer’s explanation is an opinion until the numbers match.

Test result

In DuckDB, one join multiplied the sample rows. The row count and reference total exposed the mismatch. The corrected query returned the expected total.

Limits

  • The static checks are heuristics. They parse the text and raise false alarms, for example on a legitimate DISTINCT or <>. A clean result proves nothing.
  • The checker parses the DuckDB dialect only. T-SQL or Spark SQL may not parse; the project then reports “cannot analyse” (P001), and it does the same for EXEC (A001). It never reports such SQL as clean.
  • A fan-out is invisible in the text. Only the row count or a reconciled total shows it. Case 1 is flagged by nothing in the static check.
  • The trusted values here are checked by hand on a handful of rows. On real tables you need a number you trust from outside the query.
  • The row-count guard fits lookup-style joins. If you expect a join to return more rows than the base table, as in a payments report, compare against the expected count instead.
  • Cost is not measured. The project cannot tell you what a query costs in Fabric. The Microsoft pages read here describe how consumption is measured and reported. The project does not turn that into a cost per query.
  • A reviewer agent is a second opinion. It reads the same text you do and cannot see your data unless you run its queries.
  • Query insights is after the fact. A query appears there once it has completed, and it covers queries run in a user’s context, not system queries.

Sources

Author

Rodrigo Lombana Reina, data engineer. Personal opinions. Checked against the documentation on 2026-11-29.

Questions

How do I review SQL written by an AI before I run it?

Read it first, then check numbers, not wording. Flag any write such as INSERT, UPDATE, DELETE or DROP, read every join, count rows before and after, and reconcile one total you already trust. Run it under a read-only login on a sample. A second reviewer agent gives an opinion, not proof.

How do I know a join multiplied my rows?

Count the rows of the table you started from and the rows of the joined result. For a lookup-style join the two numbers must match. In the project's DuckDB 2.0.1 run, 3 orders became 4 rows, so SUM returned 450 where the trusted total was 350. A higher count means the join key is not unique on one side.

Does SELECT DISTINCT fix duplicates caused by a join?

No, it can hide them and still leave the total wrong. In the project, SUM(DISTINCT amount) returned 250 where the correct total was 350, because two orders had the same amount of 100 and collapsed into one. Aggregate the many side first, then join, which returned 350.

Why does NOT EQUAL drop rows with NULL in SQL?

Because a comparison with NULL is not true, so the row is filtered out. In the project's DuckDB 2.0.1 run, with statuses paid, paid, cancelled and NULL, status <> 'cancelled' counted 2, while status IS DISTINCT FROM 'cancelled' counted 3. Read every filter for NULL before trusting a count.

Why does BETWEEN lose the last day of the month?

BETWEEN includes both ends, and a bare date means midnight. In the DuckDB 2.0.1 run, BETWEEN '2026-11-01' AND '2026-11-30' counted 3 of 4 events, missing one at 16:45 on 30 November. A half-open range, created_at >= '2026-11-01' AND created_at < '2026-12-01', counted all 4.

Can I see what a query cost in Fabric Warehouse?

Partly, and only afterwards. Query insights lists completed queries for 30 days, with allocated CPU time and rows returned, and queries can take up to 15 minutes to appear. The Capacity Metrics app shows when consumption happened and how much. The documentation pages do not label either as preview. This project does not measure cost.

Do static SQL checks catch a fan-out join?

No. The project's static checks parse the text, and they found nothing in the fan-out query that returned 450 instead of 350. Only the row-count guard or a reconciled total shows it. Static checks are heuristics, they raise false alarms, and a clean result proves nothing.

Portrait of Rodrigo Lombana Reina

Rodrigo Lombana Reina, data engineer. Data problems solved, step by step.

About Rodrigo · The opinions and texts on this site are my own.

My LinkedIn profile