NULL logic
NULL means “no value” or “unknown”. A comparison with NULL is neither true nor false, and WHERE keeps only the rows where the condition is true. Most NULL bugs make rows vanish without an error: a list comes back empty, a sum is NULL instead of 0, a filter loses rows.
Three values: true, false and unknown
Section titled “Three values: true, false and unknown”SQL logic has a third value, NULL, read as “unknown”. Any comparison with NULL gives NULL, even NULL = NULL.
What do the three comparisons return?
Guess the result first, then run the query.
SELECT NULL = NULL AS eq,
NULL IS NULL AS is_null,
NULL <> 1 AS ne;Show answer
eq and ne are NULL, is_null is true. Any comparison with NULL gives NULL (“unknown”), and WHERE keeps only TRUE. Test with IS NULL / IS NOT NULL; for “not equal, NULL included” use IS DISTINCT FROM.
This is what PostgreSQL returns for the query as it is:
| eq | is_null | ne |
|---|---|---|
| NULL | true | NULL |
AND and OR treat “unknown” with common sense. If the known part already decides the answer, the result is known:
SELECT TRUE AND NULL AS true_and_null, FALSE AND NULL AS false_and_null, TRUE OR NULL AS true_or_null, FALSE OR NULL AS false_or_null, NOT NULL::boolean AS not_null;| true_and_null | false_and_null | true_or_null | false_or_null | not_null |
|---|---|---|---|---|
| NULL | false | true | NULL | NULL |
FALSE AND unknown is false, whatever the unknown is. TRUE OR unknown is true. The other combinations stay unknown.
WHERE keeps a row only when the condition is TRUE. A NULL condition drops the row, and so does its negation:
SELECT COUNT(*) AS all_rows, COUNT(*) FILTER (WHERE refunded_at >= TIMESTAMP '2026-09-01') AS refunded_in_sep, COUNT(*) FILTER (WHERE NOT (refunded_at >= TIMESTAMP '2026-09-01')) AS not_refunded_in_sepFROM transactions;| all_rows | refunded_in_sep | not_refunded_in_sep |
|---|---|---|
| 8294 | 13 | 175 |
13 + 175 is 188, the number of refunded rows. The 8106 rows without a refund are in neither column: for them, the condition and its negation are both NULL. If “not refunded in September” must include them, write it out: refunded_at IS NULL OR refunded_at < TIMESTAMP '2026-09-01'.
IS NULL and IS DISTINCT FROM
Section titled “IS NULL and IS DISTINCT FROM”IS NULL and IS NOT NULL are the tests that always answer true or false. In the practice data, refunded_at IS NOT NULL means “refunded”, and advances_enrolled_at IS NULL means “not in the advances program”.
<> has the same problem as =. “Every merchant who did not join on 25 June”, written with <>, loses the merchants who never joined. IS DISTINCT FROM treats NULL as a normal value:
SELECT COUNT(*) FILTER (WHERE advances_enrolled_at <> TIMESTAMP '2026-06-25') AS with_ne, COUNT(*) FILTER (WHERE advances_enrolled_at IS DISTINCT FROM TIMESTAMP '2026-06-25') AS with_distinctFROM merchants;| with_ne | with_distinct |
|---|---|
| 4 | 10 |
Two of the 12 merchants joined on 25 June. Ten did not: four joined on another day, and six never joined. <> sees only the four.
NOT IN and NULL
Section titled “NOT IN and NULL”x NOT IN (a, b) means x <> a AND x <> b. If the list holds a NULL, one part is NULL, and the whole condition can never be true.
Will the query return a row?
Guess the result first, then run the query. Fix the query, then Check.
Output columns: result
SELECT 'found' AS result WHERE 1 NOT IN (2, NULL);
Show answer
No rows. 1 NOT IN (2, NULL) expands to 1 <> 2 AND 1 <> NULL, which is TRUE AND NULL, which is NULL. One NULL in a NOT IN list or subquery, and the result is empty. For “not in the list”, use NOT EXISTS.
This is what PostgreSQL returns for the query as it is:
| result |
|---|
Show the fix
SELECT 'found' AS resultWHERE NOT EXISTS (SELECT 1 FROM (VALUES (2), (NULL::int)) AS v(x) WHERE v.x = 1);| result |
|---|
| found |
With a subquery, the NULL comes from the data. One NULL merchant_id in advances is enough:
SELECT COUNT(*) AS never_advancedFROM merchantsWHERE id NOT IN (SELECT merchant_id FROM advances UNION ALL SELECT NULL);| never_advanced |
|---|
| 0 |
Without the last two lines, the answer is 6. NOT EXISTS and LEFT JOIN … IS NULL do not have this problem: see Subqueries and CTE.
Aggregates skip NULL, and no rows give NULL
Section titled “Aggregates skip NULL, and no rows give NULL”Aggregate functions ignore NULL values. COUNT(*) is the exception: it counts rows.
SELECT SUM(x) AS sum_x, AVG(x) AS avg_x, COUNT(x) AS count_x, COUNT(*) AS count_starFROM (VALUES (10), (NULL), (20)) AS v(x);| sum_x | avg_x | count_x | count_star |
|---|---|---|---|
| 30 | 15.0000000000000000 | 2 | 3 |
The average is 15, not 10: the NULL row is not in the denominator. Conditional aggregation uses this on purpose. It is a bug only when you do not expect it.
The second rule: an aggregate over no rows returns NULL. SUM of nothing is NULL, not 0. COUNT is the exception again and returns 0.
mer_02 has no advances at all. What will SUM return?
Guess the result first, then run the query. Fix the query, then Check.
Output columns: advanced_usd
Tables, columns and how they connect
advances — advances: early payouts to merchants against marketplace payouts that have not arrived yet
merchant_id— → merchants.idamount_usd— amount advanced (principal)
| merchant_id | amount_usd |
|---|---|
| mer_01 | 48.75 |
| mer_01 | 96.34 |
| mer_01 | 68.38 |
"Today" is 2026-09-30 00:00 UTC. All times are UTC. Every run is rolled back, so you cannot break the data.
SELECT SUM(amount_usd) AS advanced_usd FROM advances WHERE merchant_id = 'mer_02';
Show answer
NULL, not 0: the sum of an empty set is NULL. For money, and after a LEFT JOIN, write COALESCE(SUM(…), 0).
This is what PostgreSQL returns for the query as it is:
| advanced_usd |
|---|
| NULL |
Show the fix
SELECT COALESCE(SUM(amount_usd), 0) AS advanced_usdFROM advancesWHERE merchant_id = 'mer_02';| advanced_usd |
|---|
| 0 |
Refunded amounts per channel. What is in the promo row?
Guess the result first, then run the query. Fix the query, then Check.
Output columns: channel, refunded_usd
Tables, columns and how they connect
transactions — one row = one paid (or trial) period of a subscription
channel— north_market / south_market (partner marketplaces) / web (own checkout) / promo (free access, price 0)charged_usd— what the customer paid (gross)refunded_at— when the money was returned; NULL = no refund; "refunded" = refunded_at IS NOT NULLis_test— test purchase: exclude it from business numbers
| channel | charged_usd | refunded_at | is_test |
|---|---|---|---|
| north_market | 79.99 | NULL | false |
| north_market | 6.99 | NULL | false |
| north_market | 39.99 | 2025-02-04 15:18:13 | false |
"Today" is 2026-09-30 00:00 UTC. All times are UTC. Every run is rolled back, so you cannot break the data.
SELECT channel,
SUM(charged_usd) FILTER (WHERE refunded_at IS NOT NULL) AS refunded_usd
FROM transactions
WHERE NOT is_test
GROUP BY channel
ORDER BY channel;Show answer
NULL. Promo access has no refunds, and SUM over an empty set is NULL. COUNT(*) FILTER would return 0. For money, write COALESCE(SUM(x) FILTER (WHERE …), 0).
This is what PostgreSQL returns for the query as it is:
| channel | refunded_usd |
|---|---|
| north_market | 1713.96 |
| promo | NULL |
| south_market | 947.45 |
| web | 355.79 |
Show the fix
SELECT channel, COALESCE(SUM(charged_usd) FILTER (WHERE refunded_at IS NOT NULL), 0) AS refunded_usdFROM transactionsWHERE NOT is_testGROUP BY channelORDER BY channel;| channel | refunded_usd |
|---|---|
| north_market | 1713.96 |
| promo | 0 |
| south_market | 947.45 |
| web | 355.79 |
The same NULL appears after a LEFT JOIN for every row without a match: see LEFT JOIN and zeros.
COALESCE: the first value that is not NULL
Section titled “COALESCE: the first value that is not NULL”COALESCE(a, b, c) returns the first argument that is not NULL. Typical uses: 0 for an empty sum, a label for a missing value, a fallback column such as COALESCE(refunded_at, end_time).
NULLIF(a, b) does the opposite: it returns NULL when a = b. Its main use is a safe division. x / NULLIF(n, 0) gives NULL instead of an error when n is 0.
One type for every branch
Section titled “One type for every branch”COALESCE and CASE return one value of one type. PostgreSQL chooses the type from the branches. When one branch is a timestamp, it tries to read the text label as a timestamp too:
SELECT id, COALESCE(advances_enrolled_at, 'not enrolled') AS enrolledFROM merchants;ERROR: invalid input syntax for type timestamp: "not enrolled"CASE behaves the same way. CASE WHEN is_test THEN 'test purchase' ELSE revenue_usd END fails with invalid input syntax for type numeric: "test purchase". The fix is to make every branch text:
SELECT transaction_id, CASE WHEN is_test THEN 'test purchase' ELSE CAST(revenue_usd AS TEXT) END AS priceFROM transactionsWHERE transaction_id IN ('t_000001', 't_000115')ORDER BY transaction_id;| transaction_id | price |
|---|---|
| t_000001 | 79.99 |
| t_000115 | test purchase |
Practice
Section titled “Practice”Every merchant with the date they joined the advances program as text (YYYY-MM-DD), or 'not enrolled'.
Output columns: id, enrolledOrder: ORDER BY id
Tables, columns and how they connect
merchants — merchants (12 rows): businesses that sell subscriptions on the platform
id— key: mer_01 …advances_enrolled_at— when the merchant joined the advances program; NULL = not enrolled
| id | advances_enrolled_at |
|---|---|
| mer_01 | 2026-06-25 00:00:00 |
| mer_02 | NULL |
| mer_03 | 2026-06-19 00:00:00 |
"Today" is 2026-09-30 00:00 UTC. All times are UTC. Every run is rolled back, so you cannot break the data.
-- your query here
Show answer
Reference
SELECT id, COALESCE(CAST(CAST(advances_enrolled_at AS DATE) AS TEXT), 'not enrolled') AS enrolledFROM merchantsORDER BY id;Expected output
| id | enrolled |
|---|---|
| mer_01 | 2026-06-25 |
| mer_02 | not enrolled |
| mer_03 | 2026-06-19 |
| mer_04 | 2026-06-18 |
| mer_05 | not enrolled |
| mer_06 | not enrolled |
| mer_07 | 2026-06-25 |
| mer_08 | not enrolled |
| mer_09 | 2026-06-16 |
| mer_10 | not enrolled |
| mer_11 | 2026-06-15 |
| mer_12 | not enrolled |
COALESCE takes the first value that is not NULL, but all its arguments must have one type. Cast the date to text first. Without the cast, the query fails: invalid input syntax for type timestamp: "not enrolled". CAST(CAST(x AS DATE) AS TEXT) gives YYYY-MM-DD; to_char(x, 'YYYY-MM-DD') does the same.
Further reading
Section titled “Further reading”- Comparison functions and operators —
IS NULL,IS DISTINCT FROMand the other predicates. - Logical operators — truth tables of
AND,ORandNOTwith NULL. - COALESCE and NULLIF — the two NULL helpers.
- NOT IN — how a NULL in the subquery changes the result.
- UNION, CASE and related constructs — how PostgreSQL chooses one result type for
CASEandCOALESCE.
Related topics
Section titled “Related topics”- LEFT JOIN and zeros — NULLs after a join without a match, and
COALESCEback to 0. - Subqueries and CTE —
NOT EXISTS, the safe way to say “never”. - Conditional aggregation —
AVGwithCASErelies on aggregates skipping NULL. - Grouping and counting —
COUNT(*)againstCOUNT(col). - Money and ledgers — a balance must be 0, not NULL.
Site content: CC BY 4.0. Code: MIT. The exercises run in your browser: PostgreSQL by PGlite, Python by Pyodide.