SQL NULL Values: IS NULL, COALESCE and Three-Valued Logic
NULL is SQL's marker for a missing or unknown value. Two customers in our database have no email address on file, so their email column is NULL. It is not zero and it is not an empty string; it means "we do not know".
Comparisons with NULL are unknown
Because NULL means unknown, any comparison with it is also unknown, written as NULL too. Is an unknown email equal to 'ava@example.com'? Unknown. Is it not equal? Also unknown. WHERE keeps only rows where the condition is true, so a row with NULL matches neither email = 'x' nor email <> 'x'. Even NULL = NULL is unknown, as the last query in the example shows with its empty value. This is called three-valued logic: true, false and unknown.
IS NULL and IS NOT NULL
To test for missing values, use the special operators IS NULL and IS NOT NULL. WHERE email IS NULL finds the customers without an email. IS returns true or false, never unknown, which is why the example's second column shows 1 (SQLite's way of printing true).
Expected output
name | email Sofia Patel | Lucas Meyer | all_rows | with_email 6 | 4 name | contact Ava Brooks | ava@example.com Sofia Patel | no email equal_test | is_test | 1
NULL in aggregates
count(*) counts rows, while count(email) counts only the rows where email is not NULL. That gives a quick way to measure how complete a column is: 6 customers, 4 with an email. Functions like sum() and avg() also skip NULLs, so an average is taken only over known values.
Replacing NULL with COALESCE
coalesce(a, b, ...) returns the first argument that is not NULL. coalesce(email, 'no email') shows a readable placeholder instead of a blank. SQLite also has ifnull(a, b), the two-argument version; other databases spell it ISNULL or NVL, but COALESCE is standard and works everywhere.
Arithmetic and text with NULL
Most operations involving NULL produce NULL: price + NULL is NULL, and 'a' || NULL is NULL in SQLite. Wrap possibly missing values in coalesce() before combining them.
Common mistakes
- Writing
WHERE email = NULL, which never matches anything. - Being surprised that
<>filters dropNULLrows. - Using
NOT IN (subquery)when the subquery can returnNULL; the whole condition becomes unknown and returns no rows.
Summary
NULLmeans unknown; comparisons with it are unknown, not true.- Test with
IS NULL/IS NOT NULL. count(column)skipsNULLs;count(*)counts rows.coalesce()substitutes a default forNULL.
Quiz: NULL values