TablePad

AI-written SQL is usually wrong in one quiet way: join fan-out. Two cheap checks catch it

On a 419-order sample store, one extra JOIN turns $83,925.60 of revenue into $148,112.00, with no error. Here are two checks, a row count and a contrast query, that flag this and empty-result bugs.

5 min read

Text-to-SQL rarely fails with a syntax error. Models are good at syntax. When AI-written SQL is wrong, it's usually wrong the way a tired analyst's SQL is wrong: it runs, returns a plausible number, and the number is off.

I build TablePad, a database client whose canvas lets an AI agent answer questions with SQL steps you can see and edit. Two checks have caught more bad answers than anything else I've tried. Neither needs a smarter model, and both work on queries a human wrote too.

All numbers below come from the sample database that ships with TablePad: a small outdoor-gear store with 80 customers, 419 orders and 614 order lines. I loaded it into Postgres 16 to run them.

The 76% revenue bug

Question: what was revenue from delivered and shipped orders?

SELECT ROUND(SUM(total)::numeric, 2) AS revenue
FROM orders
WHERE status IN ('delivered', 'shipped');
-- 83,925.60

Now the same question, but the query also joins order_items. Maybe the next step will filter by product category, or maybe the model just likes being thorough:

SELECT ROUND(SUM(o.total)::numeric, 2) AS revenue
FROM orders o
JOIN order_items oi ON oi.order_id = o.id
WHERE o.status IN ('delivered', 'shipped');
-- 148,112.00

Same filter, a plausible number, no warning. It's 76% too high, because orders.total is an order-level number and the join repeats every order once per line item. 162 of the 419 orders have more than one line, so they're counted two or three times.

It isn't even wrong by a constant you could spot and divide out:

Channel With the join Correct Inflated by
web 84,165.40 46,977.60 1.79×
mobile 39,540.80 23,508.90 1.68×
marketplace 24,405.80 13,439.10 1.82×

Averages go wrong too. Average order value comes out as 264.96 instead of 222.03, because multi-line orders get extra weight. COUNT(DISTINCT o.id) fixes the order count, but nothing fixes the sum short of not joining, or aggregating the line items before the join.

BI people call this a fan trap. Models walk into it because the schema invites them. There's a foreign key from order_items to orders, and a join along a foreign key looks like the responsible thing to do.

Check 1: count the rows before and after the join

The idea is simple. Run the same query without its joins, keeping the same base table and the same filters, and compare row counts. If the joined version has more rows, something on the joined side isn't unique.

-- the query's FROM/WHERE without the join
SELECT COUNT(*) FROM orders o
WHERE o.status IN ('delivered', 'shipped');                      -- 378

-- the same, with the join
SELECT COUNT(*) FROM orders o
JOIN order_items oi ON oi.order_id = o.id
WHERE o.status IN ('delivered', 'shipped');                      -- 559

378 became 559, so the join multiplied rows. To tell the person why, check whether the join key on the joined side is unique, and show a few offenders:

SELECT order_id AS key_value, COUNT(*) AS n
FROM order_items
WHERE order_id IS NOT NULL
GROUP BY order_id
HAVING COUNT(*) > 1
ORDER BY n DESC
LIMIT 5;
-- 22 ×3, 390 ×3, 351 ×3, 299 ×3, 42 ×3

In TablePad the agent writes the join-less version of every joining step and names the join keys it expects to be unique. The app runs both counts and the key query itself and shows the result under the step:

A query step joining orders to order_items, with a warning that the join grew the rows from 378 to 559 because order_items.order_id is not unique
The check runs next to the step and names the key that isn't unique.

The mistake that makes this check useless

Count the rows that go into the aggregation, not the rows that come out.

If you run the check on the final GROUP BY channel query, you compare 3 channels with the join against 3 channels without it. The check passes, and it passes on exactly the queries where fan-out does the most damage. I learned this from my own check, which looked at the 76% query and reported "Joins kept the row count in check (378 before, 3 after)".

There are two ways to get this right:

  • Count the pre-aggregation rows. Strip the SELECT list, GROUP BY and ORDER BY, and count what's left of FROM … WHERE. A SQL parser does this reliably; asking the model for the two COUNT(*) queries works too.
  • Keep joins and aggregation in separate steps. First a step that produces row-level data (the join), then a step that aggregates it. Each step's row count then means something on its own. That's the shape in the screenshot: order_lines is checked, and the GROUP BY reads from it.

And if the count drops after an inner join, that's worth a note too. Rows without a match were silently removed, which is just as likely to make a total wrong.

Check 2: when a query returns nothing, ask whether it can return anything

The second quiet failure is the empty result. "No orders for that customer" and "this query can never return a row" look identical. Both are 0 rows.

Here's a real one. In the SQLite version of the same database, ordered_at holds full timestamps like 2026-03-14T09:12:00Z. Asked for orders placed on March 14, a model writes:

SELECT id, customer_id, status, total
FROM orders
WHERE ordered_at = '2026-03-14';
-- 0 rows

Zero rows. Was it a quiet day? No: one order was placed that day. The comparison is between a timestamp string and a date string, so it can never match.

The check is a contrast query: the same query with the specific value swapped for a case that certainly has data, written without parameters:

SELECT id, customer_id, status, total
FROM orders
WHERE ordered_at = '2026-09-28';   -- a day that had 3 orders
-- 0 rows

If the contrast query finds rows, the original empty result is real: that record has none. If the contrast query is empty too, the query is broken, and the step should be retried instead of reported. Here it's broken, and the fix is WHERE date(ordered_at) = '2026-03-14', which returns the one order.

A step that returned 0 rows, marked as failed because the same query on a normal case also returned 0
Zero rows, and zero rows on a day that certainly had orders: the query is wrong, not the data.

Where does "a case that certainly has data" come from? The model usually knows. It has just explored the table, or it can pick the most recent row. You can also derive it mechanically: read one real value of the filtered column (SELECT ordered_at FROM orders ORDER BY id DESC LIMIT 1) and substitute it. Either way, keep three rules:

  • The contrast query runs only when the result is empty. It costs nothing on the happy path.
  • It's standalone (no parameters) and goes through the same read-only guard as every other query.
  • It needs a small row limit. You only need to know whether it finds anything.

What it costs

Very little. The join check is two COUNT(*) queries plus one GROUP BY … HAVING per expected-unique key, and only for steps that join. The contrast query runs only on empty results. Both reuse the main query's parameters and go through the same read-only path:

if (result.rowCount === 0 && step.contrastSql) {
  const contrast = await runQuery(step.contrastSql, {}, { maxRows: 5 });
  if (contrast.rowCount > 0) note('ok', 'This record really has none.');
  else fail('0 rows here and 0 rows on a normal case: the query is probably wrong.');
}

if (step.joinCheck) {
  const before = await countRows(step.joinCheck.baseSql, bindings);   // no joins
  const after = await countRows(rowLevelSql(step), bindings);          // before any GROUP BY
  if (after > before) warn(`The join grew the rows from ${before} to ${after}.`, await duplicateKeys(step.joinCheck.keys));
}

countRows wraps the query as SELECT COUNT(*) AS n FROM (…) AS _c, so it works for any SELECT the model writes.

What these checks don't catch

They're narrow on purpose. They won't tell you that status 3 means "delivered" in this database and "returned" in the next one, that a date range is off by a timezone, or that NOT IN against a subquery containing a NULL returns nothing. For those, the best tool I've found is boring: write the facts down once ("orders.total already includes every line item; don't add order_items on top of it") and put them in front of the model every time.

But fan-out and impossible filters are the two failures that hide best, because their output looks exactly like a correct answer. Two COUNT(*) queries and one contrast query are a cheap way to make them visible.