r/SQL • u/Plane_Big_5912 • 1h ago
Discussion diagnosing wrong SQL by testing one edit mutations on the data (and the fan out case that shrinks the result)
i'm working on an automated SQL grader on DuckDB for a game. pass/fail grading is the straightforward part. explaining why a wrong query is wrong is getting difficult, because "93 rows, expected 13" doesn't really tell a player much.
guessing the mistake from the SQL text didn't work for me, there are too many ways to write the same thing. so the checker only uses the query to list candidate edits (each join, each aggregate). the data decides:
- unmatched rows: flip one INNER JOIN to LEFT, or move the outer table's WHERE conditions into its ON. if that single edit makes the result match the expected rows exactly, that join is the mistake.
- NULLs: swap COUNT(*) and COUNT(col), or AVG(x) and AVG(COALESCE(x, 0)). same exact-match test.
- fan-out: change the data instead of the query. keep one row per join key in the repeated table, then run the learner's query and the reference on that. if they now agree, and the original result was inflated, the duplicates were it. then it shows the source rows that got repeated.

the screenshot: "users with a completed deposit and zero withdrawals, each user once". the join to deposits repeats a user once per deposit, so one user shows up 11 times. the panel names the key and the repeated rows.
the one i was stuck on until this week: fan-out that shrinks the result. one audit problem compares SUM(fills.quantity) > SUM(orders.quantity) after the join, so the order side gets inflated and the query returns fewer rows than it should. my inflation check never fired, because nothing was inflated in the output.
what ended up working: first a cheap probe per joined table, count(t.rowid) - count(distinct t.rowid), to see if that table's rows repeat at all after the join. if one does, rewrite each aggregate over it so every source row counts once (in duckdb: list_sum(map_values(map_from_entries(list(distinct row(t.rowid, x)))))), rerun, and require an exact match like the other edits. it hasn't misfired on the problems i've run it on, but that's my own test set, so take it with salt.
two things i'd like input on:
- is there a cleaner way to make an aggregate count each source row once after a join? SUM(DISTINCT x) is wrong when two different rows hold the same value, which is why i went through rowid. curious if other engines have something tidier.
- if you review SQL regularly, what common bug would completely fool a single-edit checker like this (besides compound mistakes, which already break it)?