IS NULL / IS NOT NULL example
SELECT id, name, email
FROM customers
WHERE email IS NULL
ORDER BY id;The condition does not try to guess why the email is missing. It only checks that the stored value is unknown.
Check the result with small data
One customer has no email and another has it as an empty string.
WITH customers(name, email) AS (
VALUES ('Amy', 'amy@test.local'), ('Liam', NULL), ('Eva', '')
)
SELECT name FROM customers WHERE email IS NULL;| name |
|---|
| Liam |
IS NULL finds only Liam: NULL is not the same as an empty string. A comparison email = NULL would not return that row.
Check your understanding: Which query would you use to find an email that is not NULL?
Show answer
WHERE email IS NOT NULL. With this data it would return Amy and Eva: Eva's empty string is a value that is present.
How IS NULL / IS NOT NULL is used
Do not write column_name = NULL. An ordinary comparison with NULL gives an unknown result, not true.
What changes from case to case
In SQL, a condition can be true, false, or unknown. WHERE keeps only the rows for which the condition is true. That is why email = NULL does not find the rows with no email: the result of that comparison is unknown.
The same rule applies to expressions such as NOT (email = NULL). Negating an unknown result still gives unknown. Use the dedicated predicate that says what you mean.
Common mix-ups with IS NULL / IS NOT NULL
Confusing NULL with an empty string
email IS NULL does not find ''. If your system allows both states, decide whether they mean different things and filter for each one explicitly.
Using NOT IN when the list can contain NULL
An unknown value in the list can make the whole comparison unknown. For complex exclusions, review the data and consider NOT EXISTS.