NULL in NOT IN vs NOT EXISTS and LEFT JOIN filters
Given users(id): (1),(2) and banned(user_id): (2),(NULL), what does Query A return vs Query B?
Code Snippet
-- Query A
SELECT id FROM users WHERE id NOT IN (SELECT user_id FROM banned);
-- Query B
SELECT u.id FROM users u WHERE NOT EXISTS (
SELECT 1 FROM banned b WHERE b.user_id = u.id
);Expected Output & Explanation
Query A: 0 rows (empty)
Query B: 1 row (id = 1) In SQL three-valued logic, 1 NOT IN (2, NULL) evaluates to (1 <> 2) AND (1 <> NULL) -> TRUE AND UNKNOWN -> UNKNOWN, so WHERE filters out every row! NOT EXISTS tests only whether matching rows exist and safely returns user 1.
Follow-up Interview Question · What happens if you put a filter on the right table of a LEFT JOIN inside WHERE instead of ON?
Module Context & References
SQL & PostgreSQL · Query behavior & trap drills Predict query results for NULL logic, JOIN filters, aggregates and window functions
Personal Notes · Markdown