Video in progress
Why does `WHERE deleted_at = NULL` return no rows?
SELECT count(*) FROM users WHERE deleted_at = NULL; -- 0
SELECT count(*) FROM users WHERE deleted_at IS NULL; -- 1240
NULL means "unknown value", so any = or <> comparison with it yields NULL, not true. To test for NULL you write IS NULL or IS NOT NULL.
📖 Answer
SQL uses three-valued logic: true, false and NULL (unknown). WHERE lets through only the rows that evaluate to true. deleted_at = NULL always evaluates to NULL, so no row passes. There's no error either, just an empty result, so this bug can go unnoticed for a long time.
The same rule shows up elsewhere:
SELECT NULL = NULL; -- NULL, not true
SELECT 5 + NULL; -- NULL
SELECT 'a' || NULL; -- NULL
SELECT coalesce(NULL, 0); -- 0 — supplies a default value
If you want to compare two columns and treat NULLs as equal, PostgreSQL has IS NOT DISTINCT FROM:
WHERE a.middle_name IS NOT DISTINCT FROM b.middle_name
The Java side has a similar trap: in Spring Data, findByDeletedAt(null) builds an IS NULL query, but if you pass null to = :param in a hand-written JPQL query, you get an empty result.
Sign up to mark studied questions and save your progress.