Skip to content

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.

SQL logic has a third value, NULL, read as “unknown”. Any comparison with NULL gives NULL, even NULL = NULL.

SQLTrap: what will it return?

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:

eqis_nullne
NULLtrueNULL

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_nullfalse_and_nulltrue_or_nullfalse_or_nullnot_null
NULLfalsetrueNULLNULL

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_sep
FROM transactions;
all_rowsrefunded_in_sepnot_refunded_in_sep
829413175

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 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_distinct
FROM merchants;
with_newith_distinct
410

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.

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.

SQLTrap: what will it return?core

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 result
WHERE NOT EXISTS (SELECT 1 FROM (VALUES (2), (NULL::int)) AS v(x) WHERE v.x = 1);
result
found
1 row

With a subquery, the NULL comes from the data. One NULL merchant_id in advances is enough:

SELECT COUNT(*) AS never_advanced
FROM merchants
WHERE 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_star
FROM (VALUES (10), (NULL), (20)) AS v(x);
sum_xavg_xcount_xcount_star
3015.000000000000000023

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.

SQLTrap: what will it return?core

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.id
  • amount_usd — amount advanced (principal)
merchant_idamount_usd
mer_0148.75
mer_0196.34
mer_0168.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_usd
FROM advances
WHERE merchant_id = 'mer_02';
advanced_usd
0
1 row
SQLTrap: what will it return?

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 NULL
  • is_test — test purchase: exclude it from business numbers
channelcharged_usdrefunded_atis_test
north_market79.99NULLfalse
north_market6.99NULLfalse
north_market39.992025-02-04 15:18:13false

"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:

channelrefunded_usd
north_market1713.96
promoNULL
south_market947.45
web355.79
Show the fix
SELECT channel,
COALESCE(SUM(charged_usd) FILTER (WHERE refunded_at IS NOT NULL), 0) AS refunded_usd
FROM transactions
WHERE NOT is_test
GROUP BY channel
ORDER BY channel;
channelrefunded_usd
north_market1713.96
promo0
south_market947.45
web355.79
4 rows

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.

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 enrolled
FROM 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 price
FROM transactions
WHERE transaction_id IN ('t_000001', 't_000115')
ORDER BY transaction_id;
transaction_idprice
t_00000179.99
t_000115test purchase
SQLWrite a query

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
idadvances_enrolled_at
mer_012026-06-25 00:00:00
mer_02NULL
mer_032026-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 enrolled
FROM merchants
ORDER BY id;

Expected output

idenrolled
mer_012026-06-25
mer_02not enrolled
mer_032026-06-19
mer_042026-06-18
mer_05not enrolled
mer_06not enrolled
mer_072026-06-25
mer_08not enrolled
mer_092026-06-16
mer_10not enrolled
mer_112026-06-15
mer_12not enrolled
12 rows

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.

Site content: CC BY 4.0. Code: MIT. The exercises run in your browser: PostgreSQL by PGlite, Python by Pyodide.