Why = NULL Never Matches in SQL
A comparison to NULL returns 'unknown', not true, so WHERE quietly drops the row.
The symptom
You filter for missing values with where phone = null (or
where status != 'shipped') and get back
fewer rows than expected or none at all. No error, just a
wrong answer.
Why it happens
In SQL, NULL is a marker for a missing or unknown value.
Ordinary comparisons involving NULL evaluate to the third SQL
truth value, UNKNOWN, so phone = null is not
true. A WHERE clause keeps only rows whose
condition is true, so those rows fall out.
The same trap bites <> / !=: a row whose
value is NULL is neither equal nor unequal to your target, so a
plain status <> 'shipped' skips every null-status row.
Write status is distinct from 'shipped' instead, which treats
NULL as just another value and keeps those rows.
The fix
Use IS NULL and IS NOT NULL when you need to test
whether a value is missing. Some Garden Shop customers have no phone number
on file; run the pair below and see which version finds them.
select customer_id, first_name, phone
from customers
where phone = nullselect customer_id, first_name, phone
from customers
where phone is null
When the question is whether a value is missing, use IS NULL /
IS NOT NULL. When you need a comparison that treats nulls as
comparable values, consider IS DISTINCT FROM.
Learn more
Related
Find missing values with IS NULL.
IS NULL, COALESCE, NULLIF, and null-safe logic.
IS NULL, COALESCE, NULLIF, and null-safe equality.
Keep NULLs from silently changing filter results.
Count days out with COALESCE so unreturned movies are not skipped.
A stray NULL drops every row. Use NOT EXISTS.