man postgres/null
lesson 3 of 34 · Querying
NULL and three-valued logic
Three of the six customers were referred by nobody. This query should find them:
SELECT name
FROM customers
WHERE referred_by = NULL;name ------ (0 rows)
No rows, and no error. This one works:
SELECT name
FROM customers
WHERE referred_by IS NULL
ORDER BY id;name ------- Ada Dara Farah (3 rows)
NULL is not a value. It marks a place where a value is missing: not given,
not known yet, or not applicable. SQL treats it as “unknown”, and follows
that through consistently. Is an unknown value equal to NULL? Unknown. So
referred_by = NULL is never true for any row, and WHERE keeps only the
rows for which its condition is true. IS NULL is the operator that asks
the question you meant.
The rest of this lesson follows “unknown” through comparisons, AND, OR and
NOT, WHERE and CHECK, functions, NOT IN and aggregates. Most of it is
one rule applied again and again.
The data
The customers and orders of the first lesson, with four columns that are allowed to be NULL: a customer’s email (not everyone gave one), who referred them, when an order shipped (only shipped orders have a date), and the rating a customer gave an order (only some shipped orders are rated).
CREATE TABLE customers (
id integer PRIMARY KEY,
name text NOT NULL,
city text NOT NULL,
email text,
referred_by integer REFERENCES customers
);
CREATE TABLE orders (
id integer PRIMARY KEY,
customer_id integer NOT NULL REFERENCES customers,
ordered_on date NOT NULL,
status text NOT NULL CHECK (status IN ('paid', 'shipped', 'cancelled')),
total numeric(8,2) NOT NULL,
shipped_on date,
rating integer CHECK (rating BETWEEN 1 AND 5)
);
SELECT * FROM customers ORDER BY id;id | name | city | email | referred_by ----+-------+---------+-------------------+------------- 1 | Ada | Lisbon | ada@example.org | 2 | Ben | Porto | | 1 3 | Chen | Lisbon | chen@example.org | 1 4 | Dara | Braga | dara@example.org | 5 | Eli | Porto | | 3 6 | Farah | Coimbra | farah@example.org | (6 rows)
SELECT * FROM orders ORDER BY id;id | customer_id | ordered_on | status | total | shipped_on | rating -----+-------------+------------+-----------+-------+------------+-------- 101 | 1 | 2026-03-02 | shipped | 42.00 | 2026-03-03 | 5 102 | 2 | 2026-03-02 | shipped | 18.50 | 2026-03-04 | 103 | 1 | 2026-03-05 | cancelled | 60.00 | | 104 | 3 | 2026-03-06 | shipped | 75.25 | 2026-03-06 | 4 105 | 2 | 2026-03-09 | paid | 31.00 | | 106 | 4 | 2026-03-10 | cancelled | 12.00 | | 107 | 1 | 2026-03-12 | paid | 27.50 | | 108 | 5 | 2026-03-13 | shipped | 99.90 | 2026-03-16 | 2 109 | 3 | 2026-03-15 | shipped | 23.75 | 2026-03-15 | 110 | 4 | 2026-03-18 | paid | 64.00 | | 111 | 2 | 2026-03-20 | shipped | 42.00 | 2026-03-21 | 5 112 | 5 | 2026-03-21 | cancelled | 15.00 | | (12 rows)
The empty cells are NULLs. psql prints NULL as nothing at all, and so do
the live runs on this page, which makes it look the same as an empty
string. IS NULL tells them apart:
SELECT NULL AS a, '' AS b, NULL IS NULL AS a_is_null, '' IS NULL AS b_is_null;a | b | a_is_null | b_is_null ---+---+-----------+----------- | | t | f (1 row)
Every box on this page gives the same output live as recorded. The data is in the setup script.
Operators pass NULL through
Almost every operator and function returns NULL when an input is NULL. If one side of a comparison is unknown, so is the answer, and the same goes for arithmetic and string concatenation:
SELECT 1 = NULL AS eq, NULL = NULL AS null_eq, NULL <> NULL AS ne,
1 < NULL AS lt, NULL + 1 AS plus, 'a' || NULL AS concat; eq | null_eq | ne | lt | plus | concat
----+---------+----+----+------+--------
| | | | |
(1 row)One row of six NULLs. NULL = NULL is NULL too: two unknown values are
not known to be equal. That is the whole reason = NULL never matches, and
why IS NULL and IS NOT NULL exist as separate operators that always
return true or false.
AND, OR and NOT with an unknown
A condition in SQL has three possible outcomes: true, false and NULL. AND, OR and NOT are defined so that the answer is NULL exactly when it would depend on the unknown value:
SELECT a, b, a AND b AS "a AND b", a OR b AS "a OR b", NOT a AS "NOT a"
FROM (VALUES (1, true), (2, false), (3, NULL)) AS x(i, a),
(VALUES (1, true), (2, false), (3, NULL)) AS y(j, b)
ORDER BY i, j;a | b | a AND b | a OR b | NOT a ---+---+---------+--------+------- t | t | t | t | f t | f | f | t | f t | | | t | f f | t | f | t | t f | f | f | f | t f | | f | | t | t | | t | | f | f | | | | | | (9 rows)
Read the rows with one blank. false AND NULL is false, because an AND
with one false side is false whatever the other side is. true OR NULL is
true for the same reason. But true AND NULL and false OR NULL depend on
the missing value, so they are NULL. And NOT NULL (the operator applied
to an unknown, not the constraint) is NULL: the opposite of unknown is
still unknown.
WHERE keeps only true
WHERE has two choices per row, keep or drop, and three possible answers. It keeps a row only when the condition is true. False and NULL both drop it. Step through a condition with an OR on every order: “rated 4 or better, or shipped within a day of the order”.
The condition rating >= 4 OR shipped_on - ordered_on <= 1 evaluated on each of the 12 orders. Six orders have NULL on both sides and are dropped; order 102 is NULL OR false, also dropped; order 108 is false OR false, dropped; orders 101, 104, 109 and 111 are kept. Order 109 has a NULL rating and is kept because its other side is true. (This figure steps through a recorded run; it needs JavaScript.)
Each part of the condition is a column of one query, run against
PostgreSQL 19.0 by the lesson’s trace.py, and the rows the figure keeps
are checked against what the real WHERE returns. The outlined row is the
one being evaluated, and dropped rows are struck through. NULLs are written
out here; psql shows them as empty cells.
SELECT id, rating, shipped_on - ordered_on AS days
FROM orders
WHERE rating >= 4 OR shipped_on - ordered_on <= 1
ORDER BY id;id | rating | days -----+--------+------ 101 | 5 | 1 104 | 4 | 0 109 | | 0 111 | 5 | 1 (4 rows)
Order 109 has no rating, but it shipped the same day, and NULL OR true
is true. Order 102 has no rating and took two days: NULL OR false is
NULL, and the row is gone, the same as order 108, whose condition is
plainly false.
The negation trap
Since WHERE drops NULL along with false, negating a condition does not give you the other rows. “Orders not rated 5” sounds like it includes the unrated ones:
SELECT id, rating
FROM orders
WHERE rating <> 5
ORDER BY id;id | rating -----+-------- 104 | 4 108 | 2 (2 rows)
It returns two of the ten orders without a 5. For the eight unrated orders
rating <> 5 is NULL, and so is NOT (rating = 5). Two queries, one
with WHERE c and one with WHERE NOT c, together miss every row on which
c is NULL.
IS DISTINCT FROM is a comparison that treats NULL as a value of its own:
two NULLs are not distinct, and a NULL is distinct from every non-NULL
value. It never returns NULL:
SELECT a, b, a = b AS "a = b", a IS DISTINCT FROM b AS "a IS DISTINCT FROM b"
FROM (VALUES (1, 1, 1), (2, 1, 2), (3, 1, NULL), (4, NULL, NULL)) AS t(i, a, b)
ORDER BY i;a | b | a = b | a IS DISTINCT FROM b ---+---+-------+---------------------- 1 | 1 | t | f 1 | 2 | f | t 1 | | | t | | | f (4 rows)
SELECT id, rating
FROM orders
WHERE rating IS DISTINCT FROM 5
ORDER BY id;id | rating -----+-------- 102 | 103 | 104 | 4 105 | 106 | 107 | 108 | 2 109 | 110 | 112 | (10 rows)
IS NOT DISTINCT FROM is its opposite, an = under which NULL matches
NULL. It is the comparison to use when a value that may be NULL is compared
with another that may be NULL: a query parameter that can be NULL, or an
old and a new version of a row that you want to know changed. Boolean
conditions have a similar pair: c IS TRUE and c IS NOT TRUE turn NULL
into false and true.
CHECK keeps everything but false
A CHECK constraint turns the rule around. It rejects a row only when its
condition is false, so a NULL passes. All twelve orders went into the table
past CHECK (rating BETWEEN 1 AND 5), eight of them with no rating. The
same test as a WHERE condition keeps four:
SELECT id, rating
FROM orders
WHERE rating BETWEEN 1 AND 5
ORDER BY id;id | rating -----+-------- 101 | 5 104 | 4 108 | 2 111 | 5 (4 rows)
A rating of 6 makes the condition false, and the insert fails; the DETAIL line shows the failing row.
INSERT INTO orders VALUES (113, 6, '2026-03-22', 'shipped', 20.00, '2026-03-23', 6);ERROR: new row for relation "orders" violates check constraint "orders_rating_check" DETAIL: Failing row contains (113, 6, 2026-03-22, shipped, 20.00, 2026-03-23, 6).
The two rules fit their jobs. A query should return only rows it knows
match; a constraint should reject only rows it knows are wrong. If a column
must have a value, that is what NOT NULL says, and a CHECK cannot say it
for you unless it tests IS NOT NULL itself.
coalesce and nullif
coalesce returns its first argument that is not NULL. It is how a NULL
becomes a default for display or arithmetic:
SELECT name, coalesce(email, 'no email') AS contact
FROM customers
ORDER BY id;name | contact -------+------------------- Ada | ada@example.org Ben | no email Chen | chen@example.org Dara | dara@example.org Eli | no email Farah | farah@example.org (6 rows)
nullif(a, b) does the opposite: it returns NULL if a equals b, and
a otherwise. The common use is avoiding a division by zero, which is an
error, by dividing by NULL instead, which gives NULL:
SELECT 42 / nullif(0, 0) AS ratio, coalesce(42 / nullif(0, 0), 0) AS ratio_or_zero; ratio | ratio_or_zero
-------+---------------
| 0
(1 row)String concatenation with || follows the general rule, so one NULL part
makes the whole string NULL. The concat function is an exception on
purpose: it skips NULL arguments.
SELECT name || ' <' || email || '>' AS with_pipes,
concat(name, ' <', email, '>') AS with_concat
FROM customers
ORDER BY id; with_pipes | with_concat
---------------------------+---------------------------
Ada <ada@example.org> | Ada <ada@example.org>
| Ben <>
Chen <chen@example.org> | Chen <chen@example.org>
Dara <dara@example.org> | Dara <dara@example.org>
| Eli <>
Farah <farah@example.org> | Farah <farah@example.org>
(6 rows)Aggregates skip NULLs
Aggregate functions are the big exception to “NULL in, NULL out”. count,
sum, avg, min and max ignore NULL inputs. count(*) counts rows,
whatever they hold; count(rating) counts the ratings that are there:
SELECT count(*) AS orders,
count(rating) AS rated,
sum(rating) AS points,
avg(rating) AS avg_rating,
sum(rating)::numeric / count(*) AS per_order
FROM orders; orders | rated | points | avg_rating | per_order
--------+-------+--------+--------------------+--------------------
12 | 4 | 16 | 4.0000000000000000 | 1.3333333333333333
(1 row)avg(rating) is 4: the average of the four ratings that exist. That is
usually what you want, but it is a choice. Dividing by every order, as
per_order does, treats a missing rating as zero, and gives 1.33.
The other side of skipping: an aggregate over no values at all, either no
rows or only NULLs, has nothing to add up. count returns 0, and sum,
avg, min and max return NULL: a sum of nothing is NULL, not 0. No
paid order has a rating:
SELECT count(rating) AS rated, sum(rating) AS points, coalesce(sum(rating), 0) AS points_or_zero
FROM orders
WHERE status = 'paid'; rated | points | points_or_zero
-------+--------+----------------
0 | | 0
(1 row)When a total should be 0, say so with coalesce.
NOT IN and a NULL in the list
This query looks for the customers who have not referred anyone:
SELECT name
FROM customers
WHERE id NOT IN (SELECT referred_by FROM customers)
ORDER BY id;name ------ (0 rows)
There are four such customers, and the query returns none. The subquery’s
referred_by values are 1, 1, 3 and three NULLs. x NOT IN (a, b, c) means
x <> a AND x <> b AND x <> c, and with a NULL in the list one of those
comparisons is NULL. For Ben, 2 <> 1 AND 2 <> 3 AND 2 <> NULL is
true AND true AND NULL, which is NULL, and WHERE drops him. The same
happens to everyone: a NOT IN list with a NULL in it is never true.
IN is affected too, but less visibly: x IN (...) is an OR of
equalities, so it is true when a match exists and NULL, rather than false,
when none does:
SELECT 1 IN (1, NULL) AS found, 2 IN (1, NULL) AS not_found, 2 NOT IN (1, NULL) AS not_in;found | not_found | not_in -------+-----------+-------- t | | (1 row)
The fix is to write the question as NOT EXISTS, which asks whether a
matching row exists and is always true or false. A NULL referred_by never
equals anything, so it never counts as a match:
SELECT c.name
FROM customers AS c
WHERE NOT EXISTS (SELECT 1 FROM customers AS r WHERE r.referred_by = c.id)
ORDER BY c.id;name ------- Ben Dara Eli Farah (4 rows)
Reach for NOT EXISTS by default; NOT IN with a subquery is safe only
when the subquery’s column cannot be NULL. The lesson on joins comes back
to this pattern, which is called an anti-join.
Grouping, DISTINCT and sorting
In one place SQL does treat NULLs as equal to each other: when it decides which rows belong together. GROUP BY puts all NULLs into one group, DISTINCT keeps one NULL, and ORDER BY sorts NULLs together, after every other value in ascending order:
SELECT referred_by, count(*) AS customers
FROM customers
GROUP BY referred_by
ORDER BY referred_by; referred_by | customers
-------------+-----------
1 | 2
3 | 1
| 3
(3 rows)The empty referred_by in the last row is the group of the three customers
nobody referred. Where the NULLs sort can be changed with NULLS FIRST and
NULLS LAST, which the lesson on sorting covers. A UNIQUE constraint, on
the other hand, treats NULLs as distinct by default, so a unique column can
hold any number of them; the lesson on constraints shows how to change
that.
Try it yourself
Use any box above: press “edit”, replace the query, press “run”. The queries in the answers can be pasted the same way.
- Predict each column, then check:
SELECT NULL AND false, NULL OR false, NOT (NULL = NULL), NULL IS NULL;
Answer
false, NULL, NULL, true. An AND with a false side is false; an OR whose
only other side is false depends on the NULL; NULL = NULL is NULL and
NOT keeps it NULL; IS NULL always answers true or false.
SELECT NULL AND false AS a, NULL OR false AS b, NOT (NULL = NULL) AS c, NULL IS NULL AS d;
- How many customers were not referred by Ada (id 1)? Write the query so that the customers nobody referred are counted.
Answer
Four: Ada, Dara and Farah (nobody referred them) and Eli (referred by
Chen). WHERE referred_by <> 1 counts only Eli.
SELECT count(*) AS not_referred_by_ada
FROM customers
WHERE referred_by IS DISTINCT FROM 1;
- Fix the
NOT INquery that looks for customers who never referred anyone, without usingNOT EXISTS.
Answer
Remove the NULLs from the list before NOT IN sees them:
SELECT name
FROM customers
WHERE id NOT IN (SELECT referred_by FROM customers WHERE referred_by IS NOT NULL)
ORDER BY id;
It returns Ben, Dara, Eli and Farah, like the NOT EXISTS version.
- Compute the average rating of shipped orders, counting an unrated shipped order as a 3.
Answer
Replace the NULL before the aggregate sees it, so that avg does not skip
it. The six shipped orders then average 22 / 6:
SELECT avg(coalesce(rating, 3)) AS avg_rating
FROM orders
WHERE status = 'shipped';
It returns 3.6666666666666667.
- List every customer with their email, showing
(none)for the customers without one, and anemail_domaincolumn that is NULL for them. (split_part(email, '@', 2)gives the part after the@.)
Answer
split_part of a NULL is NULL, so the domain needs no special case;
coalesce handles the display column:
SELECT name, coalesce(email, '(none)') AS email, split_part(email, '@', 2) AS email_domain
FROM customers
ORDER BY id;
Sources
The PostgreSQL 19 documentation:
- Comparison functions and operators:
IS NULL,IS DISTINCT FROM,IS TRUEand the other predicates, and why= NULLdoes not work. - Logical operators: the truth tables of AND, OR and NOT.
- Conditional expressions:
coalesceandnullif. - Constraints: a CHECK constraint is satisfied when its condition is true or NULL; NOT NULL; NULLs in unique constraints.
- Subquery expressions:
IN,NOT INandEXISTS, and what each returns when NULLs are involved. - Aggregate functions:
sum,avg,minandmaxreturn NULL when no row is selected, and ignore NULL inputs. - String functions:
concatignores NULL arguments. - Sorting rows: where NULLs sort by default.
ls postgres/
Querying
- 01 How a SELECT runs, clause by clause draftThe logical order of FROM, WHERE, GROUP BY, HAVING, SELECT, DISTINCT, ORDER BY and LIMIT, and the everyday errors it explains.
- 02 Tables and the types worth knowing draftinteger and bigint, numeric against double precision, text, boolean, uuid (including uuidv7), identity columns, and casts.
- 03 NULL and three-valued logic draftWhy x = NULL is never true, IS DISTINCT FROM, coalesce, NOT IN with a NULL in the list, and how aggregates skip NULLs.
- 04 Joins draftInner, left, right, full and cross joins; ON against USING; semi- and anti-joins with EXISTS; the rows an outer join adds.
- 05 Aggregates and GROUP BY plannedcount(*) against count(x), FILTER, ordered string_agg and array_agg, any_value, and grouping by a primary key.
- 06 Subqueries and set operations plannedScalar, IN, EXISTS, ANY and ALL subqueries, correlated subqueries, and UNION, INTERSECT and EXCEPT with and without ALL.
- 07 Sorting and paging plannedNULLS FIRST and LAST, collations, ties and FETCH ... WITH TIES, and keyset pagination instead of large OFFSETs.
- 08 Dates, times and time zones plannedtimestamp against timestamptz, the session time zone, intervals, date_trunc, and generate_series for calendars.
- 09 Changing data plannedINSERT, UPDATE and DELETE with RETURNING, including OLD and NEW values in RETURNING, and UPDATE ... FROM.
Analytical queries
- 10 Window functions plannedPARTITION BY, ORDER BY and frames; ranking, running totals and moving averages; lag, lead and first_value with IGNORE NULLS.
- 11 WITH queries plannedCommon table expressions for readability, MATERIALIZED and NOT MATERIALIZED, and data-modifying statements in WITH.
- 12 Recursive queries plannedWITH RECURSIVE over trees and graphs, the SEARCH and CYCLE clauses, and how to stop a recursion that never ends.
- 13 LATERAL plannedSubqueries and functions that see the row beside them: top N per group, and set-returning functions per row.
- 14 GROUPING SETS, ROLLUP and CUBE plannedSeveral groupings in one query, subtotals and grand totals, and telling them apart with GROUPING().
Richer data
- 15 JSONB plannedOperators, containment, jsonpath, updating documents, and the GIN indexes that make the queries fast.
- 16 SQL/JSON and JSON_TABLE plannedThe standard JSON functions: JSON_VALUE, JSON_QUERY, JSON_EXISTS, IS JSON, and JSON_TABLE to turn documents into rows.
- 17 Arrays plannedBuilding and slicing arrays, unnest WITH ORDINALITY, = ANY, array_agg, array_sort, and when a table is better.
- 18 Ranges and temporal keys plannedRange and multirange types, overlap and containment, exclusion constraints, and primary keys WITHOUT OVERLAPS.
- 19 Full-text search plannedtsvector and tsquery, configurations and dictionaries, ranking, highlighting, and indexing a search column.
Keeping data correct
- 20 Constraints plannedCHECK, NOT NULL, UNIQUE with NULLS NOT DISTINCT, foreign keys and their actions, deferrable constraints, NOT VALID.
- 21 Generated columns plannedColumns computed from others, virtual (the default) or stored, and what each costs on reads and writes.
- 22 Transactions and isolation levels plannedWhat READ COMMITTED, REPEATABLE READ and SERIALIZABLE let two sessions see, the anomalies each allows, and retrying serialization failures.
- 23 Row locks and queues plannedSELECT ... FOR UPDATE and its weaker forms, NOWAIT, SKIP LOCKED for job queues, and advisory locks.
- 24 Upsert and MERGE plannedINSERT ... ON CONFLICT DO NOTHING, DO UPDATE and DO SELECT; MERGE with WHEN NOT MATCHED BY SOURCE and RETURNING merge_action().
Performance from the query side
- 25 Indexes plannedWhat a B-tree index can answer: column order in multicolumn indexes, partial, expression and covering (INCLUDE) indexes.
- 26 GIN, GiST, BRIN and hash plannedWhich queries each index type serves, with the operators that use it: containment, overlap, nearest neighbour, ranges of a big table.
- 27 Reading EXPLAIN plannedPlan nodes, estimated against actual rows, buffers, and the questions to ask of a slow plan. How statistics feed the estimates.
- 28 Partitioning plannedRange, list and hash partitions, partition pruning in plans, and attaching and detaching partitions.
Logic and access in the database
- 29 Views and materialized views plannedNaming a query, updatable views, WITH CHECK OPTION, and refreshing a materialized view concurrently.
- 30 SQL and PL/pgSQL functions plannedFunctions and procedures, volatility, set-returning functions, and PL/pgSQL control flow and error handling.
- 31 Triggers plannedRow and statement triggers, BEFORE and AFTER, transition tables, and keeping an audit log.
- 32 LISTEN and NOTIFY plannedMessages between sessions, how they interact with transactions, and a small change feed.
- 33 Row-level security plannedPolicies that filter rows per role, USING against WITH CHECK, and the roles that bypass them.
- 34 Extensions worth knowing plannedpg_trgm, pgcrypto, citext, btree_gist, postgres_fdw and pg_stat_statements: what each adds and when to reach for it.