NULLs in joins and filters
NULL is not a value. It is the absence of one, and SQL models that with
three-valued logic: every comparison is true, false, or unknown.
Almost nobody gets this wrong in theory and almost everybody gets it wrong in code, because the rules only surface in four specific places. Here they are.
The one rule
A comparison involving NULL is unknown, and WHERE keeps only true.
SELECT NULL = NULL AS eq, NULL <> NULL AS ne, NULL = 1 AS one;
All three come back NULL, not true or false. NULL = NULL is not true —
two unknowns are not known to be equal. This is why IS NULL exists as separate
syntax: = NULL can never match anything.
Bite 1: a filter that silently drops rows
Grace has no department_id.
SELECT name, department_id FROM employee WHERE department_id <> 1 ORDER BY name;
Four rows: Carol, Dan, Erin, Frank. Grace is absent. NULL <> 1 is unknown, so
her row is not kept — and nothing in the output hints that a row was excluded
for a reason other than the one you wrote.
Two ways to include her, and they say different things:
SELECT name, department_id
FROM employee
WHERE department_id IS DISTINCT FROM 1
ORDER BY name;
IS DISTINCT FROM is <> with NULL treated as a value, so unknown becomes
true. Five rows. The portable long form is
WHERE department_id <> 1 OR department_id IS NULL.
Bite 2: NOT IN against a nullable column returns nothing
This is the classic, and it is worth understanding rather than memorising.
SELECT d.name
FROM department d
WHERE d.id NOT IN (SELECT department_id FROM employee);
Zero rows — and the right answer is Research. The subquery returns
{1,1,2,2,3,3,NULL}. NOT IN expands to:
d.id <> 1 AND d.id <> 1 AND d.id <> 2 AND ... AND d.id <> NULL
That last term is unknown, and true AND unknown is unknown. So for every
department the whole condition is unknown rather than true, and nothing is
returned. Add one NULL to the subquery and NOT IN stops working entirely.
NOT EXISTS does not have the problem, because it asks about the existence of
rows rather than comparing values:
SELECT d.name
FROM department d
WHERE NOT EXISTS (
SELECT 1 FROM employee e WHERE e.department_id = d.id
);
Research, correctly. Prefer NOT EXISTS over NOT IN by default. It is
correct with nulls, it usually plans at least as well, and it does not depend on
a column’s nullability — which can change under you in a migration.
The anti-join from the joins lesson is the third form and also safe:
SELECT d.name
FROM department d
LEFT JOIN employee e ON e.department_id = d.id
WHERE e.id IS NULL;
Bite 3: COUNT(*) and COUNT(column) are different questions
SELECT count(*) AS rows, count(department_id) AS with_dept FROM employee;
7 and 6. count(*) counts rows; count(x) counts rows where x is not
null. Neither is wrong — but count(column) as a stand-in for “how many rows”
is a bug waiting for the column to become nullable.
The same applies to every aggregate: avg(salary) ignores nulls, so it is the
average of the rows that have a salary, and dividing sum by count(*)
instead gives a different number.
Bite 4: NULL in GROUP BY and ORDER BY
Grouping treats all nulls as one group:
SELECT department_id, count(*) AS n
FROM employee
GROUP BY department_id
ORDER BY department_id NULLS FIRST;
Four groups, and NULL is one of them with Grace in it. That is the opposite of
the comparison rule — two nulls are not equal, but they do group together,
because grouping uses “not distinct” rather than =. The same applies to
DISTINCT and to UNION, which is why
set operations deduplicate nulls as you would hope.
Ordering needs an explicit choice. Postgres sorts nulls last by default in
ASC and first in DESC, which means flipping the direction moves them.
Write NULLS FIRST or NULLS LAST whenever the answer matters.
A checklist for review
- Any
NOT INwith a subquery — replace withNOT EXISTSunless the column is provablyNOT NULL - Any
<>or!=on a nullable column — decide whether nulls should survive - Any
count(column)— confirm you meant “non-null” and not “rows” - Any
ORDER BYon a nullable column with aLIMIT— the nulls are at one end and the limit will take them - Any outer join followed by a
WHEREon the nullable side — the joins lesson covers why that re-inners it
Try it
The NOT IN example is the one to run yourself in the
SQL playground. Delete Grace’s row first
(DELETE FROM employee WHERE id = 7) and it starts returning Research, which is
how this bug reaches production: it works until the first null arrives.
Drill it with
Departments with no employees, whose
obvious NOT IN answer returns zero rows because of a single null.
For when a schema should forbid nulls outright rather than reasoning about them, see keys and constraints and the data-modelling chapters of the HLD fundamentals.
Interview questions
1. Why does NOT IN with a subquery sometimes return no rows at all?
If the subquery yields a single NULL, every comparison chain ends in true AND
unknown, which is unknown rather than true, so no row satisfies the predicate.
2. What is the difference between count(*) and count(column)?
count(*) counts rows. count(column) counts rows where that column is not
null. They differ by exactly the number of nulls.
3. Is NULL = NULL true?
No, it is unknown. Two absent values are not known to be equal. IS NULL and
IS NOT DISTINCT FROM are the operators that treat nulls as comparable.
4. Two nulls are not equal, so why do they end up in the same GROUP BY
bucket?
Grouping, DISTINCT and UNION compare with “not distinct” semantics rather
than =, under which two nulls match. Comparison operators in WHERE do not.
5. How do you write “all rows where status is not ‘closed’”, including rows
with no status?
WHERE status IS DISTINCT FROM 'closed', or WHERE status <> 'closed' OR status
IS NULL. A plain <> silently drops the null rows.
6. Where do nulls sort, and why is that a problem with LIMIT?
Postgres puts them last ascending and first descending, so reversing the sort
moves them. With a LIMIT, a page of results can be entirely nulls purely
because of the direction. Specify NULLS FIRST or NULLS LAST explicitly.
Next
Set operations — UNION, INTERSECT, EXCEPT, and the
one that is almost always the wrong default.