NULL and three-valued logic
true, false and unknown. why NULL = NULL isn't true, and how WHERE quietly drops rows.
- address
- everything.basics.null_and_three_valued_logic
- part
- part 2, one table
- chapter
- chapter 3 of 12
- reading time
- 10 min
NULL means no value here. compare anything with it, even another NULL, and the answer isn't true or false but unknown. WHERE keeps a row only when its condition is true, so a row with a NULL in the wrong place drops out of WHERE p and out of WHERE NOT p too.
ask about NULL with IS NULL and IS DISTINCT FROM, never with =.
the picture
you know how WHERE email = NULL comes back empty, even though Grace has no email? no error, no warning, just zero rows. it feels like a bug. it's the rules working exactly as written.
think of a paper form where someone left the city blank. ask a clerk "is this person's city London?" and an honest clerk says "no idea, it's blank". ask "is it not London?" and you get the same shrug. WHERE is a bouncer that only lets in a clear yes. "no idea" isn't a yes, so the blank form stays outside whichever way you phrase the question.
- SELECT name, city
- FROM customers
- WHERE city = 'London';
| name | city | saysthe condition says | WHERE |
|---|---|---|---|
| Ada Lovelace | 'London' | true | kept |
| Zoë Martin | 'Paris' | false | dropped |
| Ana Lima | '' | false | dropped |
| Grace Okafor | 'Lagos' | false | dropped |
| José Silva | null | unknown | dropped |
Ada gets in, everyone with another city gets false. José has no city, so postgres can't say whether it's London: unknown. one row is in neither result: the condition is unknown there, NOT unknown is unknown too, and WHERE only keeps true.
→ null to blank out someone's city. a row is kept only when the condition says true. unknown (dashed) is dropped just like false, so watch the in neither count.notice Ana. her city is '', an empty string, and an empty string is a value: it's not London, so she gets a clean false. only José, whose city is really missing, falls into the hole. (her '' and his NULL are the two customers first query warned you about.)
true, false and unknown
NULL isn't a value. it's a marker that says "there's no value in this cell". so when you ask postgres whether a NULL equals something, it has nothing to compare, and it answers with a NULL boolean. the standard calls that truth value unknown, and postgres stores it as NULL.
SELECT NULL = NULL AS "NULL = NULL",
NULL = 1 AS "NULL = 1",
NULL <> 1 AS "NULL <> 1",
NULL > 1 AS "NULL > 1";| NULL = NULLbool | NULL = 1bool | NULL <> 1bool | NULL > 1bool |
|---|---|---|---|
| null | null | null | null |
four NULLs. not false, not an error: unknown, every one of them.
so SQL logic has three values, and AND, OR and NOT need rules for the third one. there's a neat way to work them out: read unknown as "true or false, nobody knows which", try both, and if both give the same answer, that's the answer.
| a ╲ b | true | false | unknown |
|---|---|---|---|
| true | |||
| false | |||
| unknown |
read unknown as "true or false, nobody knows which" and try both: true AND false is false, false AND false is false. every way gives false, so unknown AND false is false.
false AND anything is false and true OR anything is true, so those cells come out definite.that's why NULL AND false is false (no matter what the NULL turns out to be, the AND fails) but NULL AND true is unknown (it hangs on the NULL). and NOT unknown is unknown: flipping a shrug gives you a shrug.
SELECT name FROM customers WHERE email = NULL;zero rows, and postgres doesn't complain:
SELECT name FROM customers WHERE email = NULL;| nametext |
|---|
the question you meant is IS NULL. it asks whether the value is missing, which always has a yes or no answer:
SELECT count(*) FROM customers WHERE email IS NULL;
SELECT id, name, email FROM customers WHERE email IS NULL ORDER BY id LIMIT 3;| countint8 |
|---|
| 46 |
| idint4 | nametext | emailtext |
|---|---|---|
| 2 | Grace Okafor | null |
| 11 | Ana Lima | null |
| 36 | Yuna Kowalski | null |
46 customers without an email, Grace first. IS NOT NULL is its opposite, and it never says unknown either.
the rows that vanish
this is the part that bites in real queries. a condition and its NOT should split a table in two. with NULLs around, they don't:
SELECT count(*) AS london FROM customers WHERE city = 'London';
SELECT count(*) AS not_london FROM customers WHERE NOT (city = 'London');
SELECT count(*) AS everyone FROM customers;| londonint8 |
|---|
| 159 |
| not_londonint8 |
|---|
| 1786 |
| everyoneint8 |
|---|
| 2000 |
159 plus 1,786 is 1,945, not 2,000. the missing 55 are the customers whose city is NULL: city = 'London' is unknown for them, NOT unknown is unknown, and WHERE turns both away. you can ask for them by name, with IS UNKNOWN, the boolean cousin of IS NULL:
SELECT count(*) FROM customers WHERE (city = 'London') IS UNKNOWN;| countint8 |
|---|
| 55 |
there they are. it's the same trap the gate showed, at the size of a real table: every report that says "everyone who isn't in London" is quietly 55 people short.
IS DISTINCT FROM
sometimes you want a comparison that treats NULL as a value like any other: two NULLs are the same, NULL and 'London' are different, and the answer is never unknown. that's IS DISTINCT FROM, and its opposite IS NOT DISTINCT FROM.
SELECT count(*) FROM customers WHERE city <> 'London';
SELECT count(*) FROM customers WHERE city IS DISTINCT FROM 'London';| countint8 |
|---|
| 1786 |
| countint8 |
|---|
| 1841 |
1,786 with <>, 1,841 with IS DISTINCT FROM: the 55 NULL cities are back. it's in the standard (SQL:1999) and postgres has had it for ages. it's the right tool for "did this column change?" between two nullable columns, where old <> new would say unknown every time one side is NULL.
it isn't the right tool for looking up one value, though. customers has a unique index on email, and = uses it. IS NOT DISTINCT FROM can't:
EXPLAIN (COSTS OFF) SELECT id FROM customers WHERE email = 'ada@example.com';
EXPLAIN (COSTS OFF) SELECT id FROM customers WHERE email IS NOT DISTINCT FROM 'ada@example.com';an index scan for =, a full sequential scan for the other one. if the value you're looking for can't be NULL, plain = already means the same thing, and it's fast. (what an index is explains the first plan.)
NOT IN with a NULL in it
x IN (a, b) is shorthand for x = a OR x = b. so x NOT IN (a, b) is x <> a AND x <> b. put a NULL in the list and one half of that AND is unknown for every row, so no row can ever get a true:
SELECT count(*) FROM products WHERE category NOT IN ('kitchen');
SELECT count(*) FROM products WHERE category NOT IN ('kitchen', NULL);| countint8 |
|---|
| 178 |
| countint8 |
|---|
| 0 |
178, then 0. a literal NULL in a list is easy to spot. a NULL that arrives through a subquery, WHERE id NOT IN (SELECT customer_id FROM ...), is not, and it empties the result just as thoroughly. that one has a chapter of its own.
where two NULLs are the same after all
so NULL = NULL is unknown. and yet the logical order chapter put three products with no category into one GROUP BY bucket. NULL has a split personality, and it depends on which question is being asked:
| place | verdict |
|---|---|
| NULL = NULL | unknown |
| NULL <> NULL | unknown |
| NULL IS NOT DISTINCT FROM NULL | true |
| GROUP BY | 1 bucket |
| SELECT DISTINCT | 1 row |
| UNION | 1 row |
| count(DISTINCT x) | 0 values |
| ORDER BY x | 1, 2, null, null |
| a UNIQUE column | 2 NULLs stored |
the rule of thumb: an operator (=, <, IN) answers unknown. an operation that sorts rows into piles (GROUP BY, DISTINCT, UNION) puts the NULLs on one pile, because it needs every row to land somewhere. ORDER BY sorts NULLs together and, in postgres, treats them as bigger than every value, so they come last (sorting with ORDER BY shows how to move them).
UNIQUE is the odd one out. it lets in as many NULLs as you like, which is how 46 customers can share a NULL email in a column marked UNIQUE: a NULL isn't known to equal anything, so it can't be a duplicate. since postgres 15 pg 15+ you can ask for the other behaviour with UNIQUE NULLS NOT DISTINCT.
and count(DISTINCT x) skips NULLs altogether, like every aggregate does, which is the next thing.
counting and adding NULLs
aggregates skip NULLs. count(*) counts rows, count(email) counts emails that are there:
SELECT count(*) AS customers, count(email) AS emails, count(city) AS cities
FROM customers;| customersint8 | emailsint8 | citiesint8 |
|---|---|---|
| 2000 | 1954 | 1945 |
2,000 customers, 1,954 emails, 1,945 cities. the same rule applies to sum, avg, min and max: a NULL isn't zero, it isn't counted at all.
SELECT sum(x), count(x), count(*), avg(x)
FROM (VALUES (1), (NULL), (3)) AS t (x);| sumint8 | countint8 | countint8 | avgnumeric |
|---|---|---|---|
| 4 | 2 | 3 | 2.0000000000000000 |
three rows, two values. the average is 4 over 2, not 4 over 3. aggregate functions has the details, including what they return when there's nothing to aggregate.
arithmetic and most functions go the other way: one NULL in, NULL out. concat is one of the few that skips them:
SELECT 'Grace ' || NULL AS glued, concat('Grace ', NULL) AS concatenated, 1 + NULL AS added;| gluedtext | concatenatedtext | addedint4 |
|---|---|---|
| null | Grace | null |
when you want a stand-in for the missing value, coalesce(email, 'no email') gives you one. it gets its own section in CASE, COALESCE and NULLIF.
one level deeperwhere NULL came from, and who still hates it
Codd described NULL and the three-valued logic that comes with it in a 1979 paper. about a decade later he wanted two kinds: one for "applicable but missing" (we don't know her phone number) and one for "doesn't apply" (she has no phone), which would have meant a four-valued logic. nobody built it. Chris Date spent years arguing that NULL should go altogether and that missing data belongs in separate tables.
SQL kept one NULL that has to mean both. so when you see one, the database can't tell you whether the value is unknown or simply doesn't exist. you can, if you write it down: a separate phone_status column, or a design with no nullable column at all. entities and relationships is where that decision gets made.
keylines
- NULL is a marker for "no value", and any comparison with it is unknown, not false.
- WHERE keeps only true. unknown rows drop out of WHERE p and WHERE NOT p alike.
- ask with IS NULL, IS UNKNOWN and IS DISTINCT FROM, never with = NULL.
- operators say unknown; GROUP BY, DISTINCT and UNION put NULLs in one pile; UNIQUE lets them all in.
- aggregates skip NULLs, arithmetic spreads them, CHECK lets them pass.