SQL
5 min read
BEGINNER
NOT IN pitfalls
Quick AnswerNOT IN can unexpectedly exclude every candidate when the comparison list contains NULL. A nonmatching value compared with an unknown list member produces UNKNOWN rather than TRUE.
Core idea
NOT IN can unexpectedly exclude every candidate when the comparison list contains NULL. A nonmatching value compared with an unknown list member produces UNKNOWN rather than TRUE.
Minimal example
sql
SELECT id FROM products WHERE id NOT IN (SELECT product_id FROM blocked_products) ORDER BY id;Expected SQLite rows:
text
(0 rows)How it works
For non-NULL product IDs, NOT IN (1, NULL) is FALSE for ID 1 and UNKNOWN for other IDs. A correlated NOT EXISTS checks whether a matching row exists and avoids this specific problem. Its treatment of NULL on the outer side can differ, so define the intended policy.
Practical example
sql
SELECT p.id FROM products AS p WHERE NOT EXISTS (SELECT 1 FROM blocked_products AS b WHERE b.product_id = p.id) ORDER BY p.id;Expected SQLite rows:
text
234Common mistake and practice
The blocked_products fixture contains 1 and NULL. Predict which products remain after excluding known blocked IDs. Compare NOT IN with NOT EXISTS and explain why they differ.