Debugging SQL Queries Step by Step
When a query surprises you, shrink it. Inspect the data, check one piece at a time, and the bug surfaces.
Not every bug throws an error. Sometimes a query runs perfectly and returnsnothing, which is its own kind of clue. The fix is to debug in small steps: strip the query back, look at the actual data, and add conditions one at a time.
The query below expects shipped orders but comes back empty. Before changing it blindly, inspect what's really in the status column. String comparisons are case-sensitive, so a capital letter is all it takes to match nothing.
-- when a result is empty, inspect the real values:
select distinct status from orders;
-- ...then fix the filter to matchSchema · Garden ShopTable · orders6 columns · 24 rows
One row per order. Unshipped orders have a null shipped_date.
The starter returns zero rows. Figure out why, then fix it so it lists everyshipped order: order_id andstatus, sorted by order_id.
- Columns: order_id, status.
- Rows: 17 shipped orders.
- String comparisons are case-sensitive, so 'Shipped' matched nothing.
Related
Use error messages as clues.
Catch silent query logic bugs.
Make queries easier to scan and debug.
Paste an error message and find the fix, from GROUP BY to constraint failures.