One of the sneakiest production SQL bugs happens when you try to find rows in Table A that are missing from Table B:
-- "Find all users who have NEVER had a cancelled order" SELECT user_id , email FROM users WHERE user_id NOT IN ( SELECT user_id FROM cancelled_orders ) ;
Enter fullscreen mode
Exit fullscreen mode
This query works fine in staging—until one guest checkout inserts a single row into cancelled_orders where user_id IS NULL . Suddenly, the query returns 0 rows !
Why NOT IN Collapses on a Single NULL
In SQL, x NOT IN (101, 102, NULL) expands to:
(x <> 101) AND (x <> 102) AND (x <> NULL) TRUE AND TRUE AND UNKNOWN ──► UNKNOWN!
Enter fullscreen mode
Exit fullscreen mode
Because WHERE only keeps rows that evaluate to TRUE (discarding both FALSE and UNKNOWN ), zero rows ever pass the filter .
Fix #1: EXCEPT (Clean Set Subtraction Across Columns)
EXCEPT (supported in SQL Server , PostgreSQL , SQLite , and MySQL 8.0.31+ ) subtracts the second result set from the first and treats NULL = NULL as…