skip to content

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.

WHERE =
wrap =
query.sql
  1. SELECT name, city
  2. FROM customers
  3. WHERE city = 'London';
each customer, the condition's answer for them, and whether WHERE keeps the row
namecitysays
Ada Lovelace'London'true
Zoë Martin'Paris'false
Ana Lima''false
Grace Okafor'Lagos'false
José Silvanullunknown
WHERE p
1 of 5
WHERE NOT p
3 of 5
in neither
1 of 5

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.

true: keptfalse: droppedunknown: dropped too
real output, postgres 18.6 (PGlite 0.5.12) · null-and-three-valued-logic
pick a condition, wrap it in NOT, and press → 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.

sqlempty db
SELECT NULL = NULL AS "NULL = NULL",
       NULL = 1    AS "NULL = 1",
       NULL <> 1   AS "NULL <> 1",
       NULL > 1    AS "NULL > 1";
output, from postgres 18.6
SELECT 1
NULL = NULLboolNULL = 1boolNULL <> 1boolNULL > 1bool
nullnullnullnull
(1 row)

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.

operator =
a AND b, for each a and b
a ╲ btruefalseunknown
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.

real output, postgres 18.6 (PGlite 0.5.12) · null-and-three-valued-logic
every cell is postgres's own answer. click one with an unknown in it: the narration tries the unknown as true and as 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.

predict the output
sql
SELECT name FROM customers WHERE email = NULL;

zero rows, and postgres doesn't complain:

sqldb=shop
SELECT name FROM customers WHERE email = NULL;
output, from postgres 18.6
SELECT 0
nametext
(0 rows)

the question you meant is IS NULL. it asks whether the value is missing, which always has a yes or no answer:

sqldb=shop
SELECT count(*) FROM customers WHERE email IS NULL;
SELECT id, name, email FROM customers WHERE email IS NULL ORDER BY id LIMIT 3;
output, from postgres 18.6
#1 · SELECT 1
countint8
46
(1 row)
#2 · SELECT 3
idint4nametextemailtext
2Grace Okafornull
11Ana Limanull
36Yuna Kowalskinull
(3 rows)

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:

sqldb=shop
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;
output, from postgres 18.6
#1 · SELECT 1
londonint8
159
(1 row)
#2 · SELECT 1
not_londonint8
1786
(1 row)
#3 · SELECT 1
everyoneint8
2000
(1 row)

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:

sqldb=shop
SELECT count(*) FROM customers WHERE (city = 'London') IS UNKNOWN;
output, from postgres 18.6
SELECT 1
countint8
55
(1 row)

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.

sqldb=shop
SELECT count(*) FROM customers WHERE city <> 'London';
SELECT count(*) FROM customers WHERE city IS DISTINCT FROM 'London';
output, from postgres 18.6
#1 · SELECT 1
countint8
1786
(1 row)
#2 · SELECT 1
countint8
1841
(1 row)

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:

sqldb=shop
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';
output, from postgres 18.6
#1 · EXPLAIN
Index Scan using customers_email_key on customers Index Cond: (email = 'ada@example.com'::text)
#2 · EXPLAIN
Seq Scan on customers Filter: (NOT (email IS DISTINCT FROM 'ada@example.com'::text))

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:

sqldb=shop
SELECT count(*) FROM products WHERE category NOT IN ('kitchen');
SELECT count(*) FROM products WHERE category NOT IN ('kitchen', NULL);
output, from postgres 18.6
#1 · SELECT 1
countint8
178
(1 row)
#2 · SELECT 1
countint8
0
(1 row)

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:

placeverdict
NULL = NULLunknown
NULL <> NULLunknown
NULL IS NOT DISTINCT FROM NULLtrue
GROUP BY1 bucket
SELECT DISTINCT1 row
UNION1 row
count(DISTINCT x)0 values
ORDER BY x1, 2, null, null
a UNIQUE column2 NULLs stored
(9 rows)
two NULLs, nine places, one captured query. comparisons ask "are these equal?" and get unknown. grouping, DISTINCT and UNION ask "are these distinct?" and decide no. a UNIQUE column decides the other way and stores both.

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:

sqldb=shop
SELECT count(*) AS customers, count(email) AS emails, count(city) AS cities
FROM customers;
output, from postgres 18.6
SELECT 1
customersint8emailsint8citiesint8
200019541945
(1 row)

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.

sqlempty db
SELECT sum(x), count(x), count(*), avg(x)
FROM (VALUES (1), (NULL), (3)) AS t (x);
output, from postgres 18.6
SELECT 1
sumint8countint8countint8avgnumeric
4232.0000000000000000
(1 row)

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:

sqlempty db
SELECT 'Grace ' || NULL AS glued, concat('Grace ', NULL) AS concatenated, 1 + NULL AS added;
output, from postgres 18.6
SELECT 1
gluedtextconcatenatedtextaddedint4
nullGrace null
(1 row)

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.