Menu

Why SQL NOT IN Silently Returns 0 Rows with NULLs (And Why EXCEPT / NOT EXISTS Wins)
📰

Why SQL NOT IN Silently Returns 0 Rows with NULLs (And Why EXCEPT / NOT EXISTS Wins)

DEV Community: sql·BigOSlate·3 days ago
#OWk6wUfZ
#devtosql#devto#dev#except#user_id
Long article (374 words) — no AI summary yet.
Reading 0:00
15s threshold

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…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.