How to Handle NULL Semantics in SQL
Work with SQL three-valued logic correctly: use IS NULL, COALESCE, and NULL-safe comparison, and avoid the comparisons that silently drop rows.
On this page
Introduction
SQL uses three-valued logic: a comparison is true, false, or unknown. NULL stands for an unknown or absent value, and any comparison with it yields unknown rather than true or false. This single rule explains most of the surprising query results people encounter: a filter that silently excludes rows, a NOT IN that returns nothing, a join that drops unmatched rows unexpectedly. Mastering NULL semantics turns those surprises into predictable behavior.
This tutorial covers the rules of three-valued logic in practice, the operators designed for NULL, how COALESCE and NULLIF normalize values, and the traps in NOT IN, outer joins, and aggregate functions. It ends with tests that seed NULL rows and assert the query includes or excludes them as intended.
Understand three-valued logic
In SQL a WHERE clause keeps a row only when its predicate evaluates to true. When the predicate is unknown, the row is excluded, exactly as if the predicate were false. So a condition like status = NULL is unknown for every row, and the query returns nothing, regardless of the data. Likewise, the negation of unknown is still unknown, so NOT (status = NULL) also returns nothing.
This is not a bug but the definition of an unknown value. The practical consequence is that you must never write = NULL or <> NULL; those are always unknown. Use IS NULL and IS NOT NULL, which are specifically true or false for a NULL value. Any predicate that might involve a NULL column must be written with NULL-aware operators, or it will silently drop rows.
-- wrong: returns no rows even when some emails are NULL
SELECT id FROM users WHERE email = NULL;
-- right
SELECT id FROM users WHERE email IS NULL;
Compare with NULL-safe operators
When you need equality that treats NULL as a value, use IS DISTINCT FROM and IS NOT DISTINCT FROM. IS DISTINCT FROM returns true when two values differ, treating two NULLs as not distinct and a NULL and a non-NULL as distinct. This is the NULL-safe equality you want when comparing two columns that may both be null, such as matching on an optional foreign key where NULL means ‘no parent’.
The ordinary = and <> operators propagate unknown, so a join condition such as a.parent_id = b.parent_id fails to match rows where parent_id is NULL, even though both sides are ‘no parent’. IS NOT DISTINCT FROM makes those rows match when that is the intent. Choose the operator that matches the meaning of a NULL in that column, and document which you intend.
-- NULL-safe equality: match rows where parent_id is NULL on both sides
SELECT a.id, b.id
FROM nodes a
JOIN nodes b ON a.parent_id IS NOT DISTINCT FROM b.parent_id
WHERE a.id <> b.id;
Normalize with COALESCE and NULLIF
COALESCE returns the first non-null argument, which is how you provide a default for display or computation without losing the underlying NULL. NULLIF returns NULL when two arguments are equal, which is how you convert a sentinel such as an empty string or a zero-flag into a proper NULL so downstream NULL handling applies uniformly.
Use COALESCE where ‘unknown’ and ‘empty’ are genuinely the same to the caller, such as a display name fallback. Use it sparingly in filters, because wrapping a column in COALESCE often prevents the planner from using an index on that column. When the distinction between unknown and empty matters, keep the NULL and handle it explicitly rather than collapsing it early.
-- display default without changing stored data
SELECT id, COALESCE(display_name, email, 'anonymous') AS name FROM users;
-- normalize an empty string sentinel into a real NULL
UPDATE contacts SET phone = NULLIF(phone, '');
Avoid the NOT IN and outer-join traps
NOT IN with a subquery is the most dangerous NULL construct. If the subquery returns any NULL, every comparison becomes unknown, and the outer query returns no rows at all. Rewrite as NOT EXISTS, which has no such behavior, or add a WHERE the column IS NOT NULL inside the subquery. Reach for NOT EXISTS by default when you want ‘rows with no match’.
Outer joins preserve unmatched rows from one side and fill the other side with NULL, so a filter on the nullable side in the WHERE clause can silently turn the outer join into an inner join. Put the condition in the ON clause to filter the joined side without dropping the preserved rows, and use IS NULL on the nullable side to find rows that had no match.
-- fragile: any NULL in the subquery returns no rows
SELECT id FROM users WHERE id NOT IN (SELECT user_id FROM bans);
-- robust
SELECT u.id FROM users u
WHERE NOT EXISTS (SELECT 1 FROM bans b WHERE b.user_id = u.id);
Handle NULL in aggregates and grouping
Most aggregate functions ignore NULL. COUNT(column) counts non-null values while COUNT(*) counts rows, which is a deliberate distinction and a frequent source of off-by-one reports. SUM and AVG skip nulls; if every value is null, SUM returns NULL and AVG returns NULL rather than zero. Use COALESCE around the aggregate when you want a numeric default.
GROUP BY treats NULLs as equal to each other and forms a single group, unlike = which would be unknown. So grouping by a nullable column produces one group for all the nulls. DISTINCT has the same null-as-equal behavior. Keep this in mind when counting distinct values or grouping by an optional field, because the null group is real and often needs a label such as ‘unset’.
SELECT COALESCE(region, 'unset') AS region, COUNT(*) AS n
FROM customers
GROUP BY region
ORDER BY n DESC;
Test rows with NULL
Seed data that deliberately includes NULL in the columns your queries filter, join, and group by, then assert the result. A test that never inserts a NULL cannot catch a NULL bug. Assert that IS NULL finds the rows, that a NULL-safe join matches them, and that the NOT IN rewrite returns the expected rows when the subquery contains a NULL.
psql -d app <<'SQL'
INSERT INTO users (id, email) VALUES (1, NULL), (2, '[email protected]');
INSERT INTO bans (user_id) VALUES (NULL);
SELECT count(*) FROM users WHERE email IS NULL; -- 1
SELECT count(*) FROM users WHERE id NOT IN (SELECT user_id FROM bans); -- 0 (NULL trap)
SELECT count(*) FROM users u WHERE NOT EXISTS (SELECT 1 FROM bans b WHERE b.user_id = u.id); -- 2
SQL
Conclusion
NULL means unknown, and unknown propagates through comparison, so = NULL and NOT IN with NULLs return nothing. Use IS NULL, IS DISTINCT FROM, COALESCE, NULLIF, and NOT EXISTS to express intent, put outer-join filters in the ON clause, and remember that grouping treats nulls as equal. Self-check by seeding NULL rows and asserting each query includes or excludes them as designed. Predictable NULL handling comes from choosing the operator that matches what a NULL means in that column.
Sources: PostgreSQL: Comparison operators and NULL, PostgreSQL: COALESCE and NULLIF, SQLite: NULL handling.
FAQ
- Why does column = NULL never match?
- NULL represents an unknown value, so the comparison of any value to NULL is unknown, not true. A WHERE clause keeps only rows where the predicate is true, so a row with a NULL column is excluded. Use IS NULL instead, which returns true for a NULL value.
- Does NOT IN work with NULLs?
- Dangerously. If the subquery in NOT IN returns any NULL, the whole comparison becomes unknown and the query returns no rows at all. Use NOT EXISTS, or filter NULLs out of the subquery, to get the result you expect.
Report a problem with this articleOpens a pre-filled issue on GitHub.