Video in progress

A query that uses `NOT IN (subquery)` suddenly started returning an empty result. What could be the cause?

SELECT id, email
FROM users
WHERE id NOT IN (SELECT referrer_id FROM referrals);

At least one NULL has appeared in the subquery result. x NOT IN (1, 2, NULL) is never true, because x <> NULL is unknown. So a single NULL empties the whole result. NOT EXISTS doesn't have this problem.

📖 Answer

For a long time everything worked, then a row with an empty referrer_id landed in the referrals table, and the query returns 0 rows.

Expand the logic: id NOT IN (5, 7, NULL) means id <> 5 AND id <> 7 AND id <> NULL. The last part is NULL, and with AND the whole expression is NULL or false, never true.

The reliable version:

SELECT u.id, u.email
FROM users u
WHERE NOT EXISTS (
    SELECT 1 FROM referrals r WHERE r.referrer_id = u.id
);

NOT EXISTS doesn't care about NULLs, and PostgreSQL runs it efficiently as an "anti join". NOT IN (subquery), especially with a big subquery, often ends up with a worse plan.

If you want to keep NOT IN, add WHERE referrer_id IS NOT NULL to the subquery. But the next developer will forget that, so making NOT EXISTS your habit is safer.

Plain IN (without the negation) has no such problem: 5 IN (5, NULL) gives true.