Skip to content
Bronze 6 min read · NULL 3 practice problems ↓

NULL and three-valued logic

Real tables have gaps: an amount nobody recorded, a city a customer never filled in. SQL marks each gap with NULL, and NULL follows its own rules, which quietly change the result of filters, counts and joins. This lesson shows those rules, and the few tools that handle NULL safely.

Foundations · SQL for data engineers · Bronze · Reading a table, lesson 2 of 3

Read first: SELECT, WHERE and ORDER BY (skip if you know it)

In plain words first

Imagine a form where one person left their age blank. Is their age 30? You cannot say yes, and you cannot say no: you do not know. Is their age the same as another person who also left it blank? Again, you do not know.

That is NULL: not zero, not empty, but unknown. Any question about an unknown value gets the answer "unknown", and SQL treats "unknown" like "no" when it decides which rows to keep. Almost every NULL surprise comes from that one idea.

NULL means unknown

NULL is not zero and not an empty string. It means "no value": the amount was never recorded, the status was never set. Because the value is unknown, anything you compute from it is unknown too, and that includes comparisons:

Spark SQL · Every comparison with NULL is NULL
SELECT NULL = NULL AS equal,
       NULL <> 1 AS not_one,
       NULL + 5 AS plus_five,
       NULL IS NULL AS is_null

Only IS NULL gives a real answer. NULL = NULL is not true: two unknown amounts are not known to be equal. This one rule explains every NULL surprise in this lesson.

Three-valued logic

A condition in SQL has three possible results: true, false and NULL (unknown). AND and OR follow common sense about what could still be decided:

ExpressionResultWhy
TRUE AND NULLNULLDepends on the unknown side
FALSE AND NULLFALSEFalse whatever the unknown is
TRUE OR NULLTRUETrue whatever the unknown is
FALSE OR NULLNULLDepends on the unknown side
NOT NULLNULLThe opposite of unknown is unknown

WHERE keeps only TRUE

WHERE keeps a row when its condition is true. False and NULL are both thrown away. So a filter that looks like it keeps "everything except cancelled" quietly drops the order whose status is missing:

Spark SQL · Order 104 disappears

Input: orders

order_idcustomer_idrestaurantcityamountstatusplaced_at
1011Spice RoutePune420delivered2026-03-01 12:10:00
1022Pizza LabDelhi650cancelled2026-03-01 19:40:00
1031Pizza LabPunenulldelivered2026-03-02 13:05:00
1043Spice RoutePune310null2026-03-03 20:15:00
1052Wok InnDelhi280delivered2026-03-04 21:00:00
1064Spice RoutePune540delivered2026-03-05 13:30:00
1079Wok InnMumbai190delivered2026-03-05 20:45:00
1081Wok InnPune360refunded2026-03-06 19:10:00
SELECT order_id, status
FROM orders
WHERE status <> 'cancelled'

Order 104 has no status, NULL <> 'cancelled' is NULL, and the row is gone. If unknown statuses should count, say so. IS DISTINCT FROM is the NULL-aware version of <>: it treats NULL as a value that is different from every non-NULL value.

Spark SQL · Keep the unknown status

Input: orders

order_idcustomer_idrestaurantcityamountstatusplaced_at
1011Spice RoutePune420delivered2026-03-01 12:10:00
1022Pizza LabDelhi650cancelled2026-03-01 19:40:00
1031Pizza LabPunenulldelivered2026-03-02 13:05:00
1043Spice RoutePune310null2026-03-03 20:15:00
1052Wok InnDelhi280delivered2026-03-04 21:00:00
1064Spice RoutePune540delivered2026-03-05 13:30:00
1079Wok InnMumbai190delivered2026-03-05 20:45:00
1081Wok InnPune360refunded2026-03-06 19:10:00
SELECT order_id, status
FROM orders
WHERE status IS DISTINCT FROM 'cancelled'

Writing WHERE status <> 'cancelled' OR status IS NULL does the same and works in every database.

NULL in counts, sums and averages

Aggregatesaggregate: A function that turns many rows into one value: count, sum, avg, min, max. With GROUP BY it gives one value per group. Learn more → skip NULLs, except COUNT(*), which counts rows:

Spark SQL · COUNT(*) against COUNT(column)

Input: orders

order_idcustomer_idrestaurantcityamountstatusplaced_at
1011Spice RoutePune420delivered2026-03-01 12:10:00
1022Pizza LabDelhi650cancelled2026-03-01 19:40:00
1031Pizza LabPunenulldelivered2026-03-02 13:05:00
1043Spice RoutePune310null2026-03-03 20:15:00
1052Wok InnDelhi280delivered2026-03-04 21:00:00
1064Spice RoutePune540delivered2026-03-05 13:30:00
1079Wok InnMumbai190delivered2026-03-05 20:45:00
1081Wok InnPune360refunded2026-03-06 19:10:00
SELECT count(*) AS orders,
       count(amount) AS with_amount,
       sum(amount) AS total,
       round(avg(amount), 1) AS average
FROM orders

There are 8 orders but only 7 amounts. The average, 392.9, is the total 2750 divided by 7, not 8: order 103 is left out, not counted as zero. Whether that is right depends on what the NULL means. If a missing amount really means "free", write avg(coalesce(amount, 0)), which divides by 8. A SUM over a group where every value is NULL is NULL, not 0.

The NOT IN trap

x NOT IN (1, 2, NULL) means x <> 1 AND x <> 2 AND x <> NULL. The last part is never true, so the whole condition is never true, and the query returns nothing. With a subquerysubquery: A query inside another query, in brackets: in FROM as a table, or in WHERE with IN or EXISTS. Learn more →, one NULL in the subquery's column is enough. Here we look for customers who referred nobody; referred_by is NULL for customers nobody referred:

Spark SQL · Returns no rows at all
SELECT name
FROM customers
WHERE customer_id NOT IN (SELECT referred_by FROM customers)

Output

(no rows)

Meera, Kabir and Zoya referred nobody, yet the query finds no one. Use NOT EXISTS, which compares row by row and is not affected by NULLs:

Spark SQL · NOT EXISTS gets it right

Input: customers

customer_idnamecitysignup_datereferred_by
1AshaPune2026-01-05null
2RaviDelhi2026-01-201
3Meeranull2026-02-021
4KabirPune2026-02-142
5ZoyaMumbai2026-03-01null
SELECT c.name
FROM customers c
WHERE NOT EXISTS (
  SELECT 1 FROM customers r WHERE r.referred_by = c.customer_id
)

Tools that handle NULL

ToolExampleResult
IS NULL, IS NOT NULLstatus IS NULLAlways true or false, never NULL
IS DISTINCT FROMstatus IS DISTINCT FROM 'cancelled'A <> that treats NULL as a value
<=> (null-safe equals)a <=> bTrue when both are NULL; Spark and MySQL. The standard form is IS NOT DISTINCT FROM
COALESCEcoalesce(status, 'unknown')The first argument that is not NULL
NULLIFamount / nullif(qty, 0)NULL when the two are equal: turns a zero divisor into NULL instead of an error
Spark SQL · Fill in and compare safely

Input: orders

order_idcustomer_idrestaurantcityamountstatusplaced_at
1011Spice RoutePune420delivered2026-03-01 12:10:00
1022Pizza LabDelhi650cancelled2026-03-01 19:40:00
1031Pizza LabPunenulldelivered2026-03-02 13:05:00
1043Spice RoutePune310null2026-03-03 20:15:00
1052Wok InnDelhi280delivered2026-03-04 21:00:00
1064Spice RoutePune540delivered2026-03-05 13:30:00
1079Wok InnMumbai190delivered2026-03-05 20:45:00
1081Wok InnPune360refunded2026-03-06 19:10:00
SELECT order_id,
       coalesce(status, 'unknown') AS status,
       coalesce(amount, 0) AS amount,
       status <=> 'delivered' AS is_delivered
FROM orders

Compare the last column with status = 'delivered': for order 104 that would be NULL, while <=> gives a clean false.

Common mistakes

  • Writing = NULL — WHERE status = NULL never matches anything, not even the NULL rows. Use IS NULL.
  • Filtering with <> and losing NULL rows — status <> 'cancelled' drops rows with no status. Use IS DISTINCT FROM or add OR status IS NULL.
  • NOT IN over a column that can be NULL — One NULL in the list or subquery makes the condition never true, and the query returns nothing. Use NOT EXISTS (or a LEFT ANTI JOINanti join: A join that keeps the left rows that have no match at all on the right. Learn more →).
  • Assuming AVG counts missing values as zero — AVG skips NULLs, so it divides by the number of non-NULL values. Decide what NULL means, and COALESCE it first if it means zero.

Key takeaways

  • Any comparison with NULL is NULL. Only IS NULL and IS NOT NULL answer true or false.
  • WHERE keeps rows where the condition is true, so conditions that are NULL drop rows silently.
  • Aggregates skip NULLs; COUNT(*) counts rows, COUNT(col) counts non-NULL values.
  • Prefer NOT EXISTS to NOT IN whenever the column might contain NULL.

Interview prep

THE QUESTION

"A dashboard counts non-cancelled orders with WHERE status != 'cancelled', and finance says the number is too low. What is wrong?"

Orders whose status is NULL are dropped: NULL != 'cancelled' is NULL, and WHERE keeps only rows where the condition is true. Count them with status IS DISTINCT FROM 'cancelled' (or ... OR status IS NULL), then ask why statuses are missing: that is usually a data quality issue upstream worth reporting.

Avoid: "Some rows must have been deleted." The rows are still there; the filter dropped them because a comparison with NULL is never true.

Follow-ups · answer out loud, then open

Follow-up"What is the difference between COUNT(*), COUNT(col) and COUNT(DISTINCT col)?"
COUNT(*) counts rows, whatever they contain. COUNT(col) counts rows where col is not NULL. COUNT(DISTINCT col) counts the different non-NULL values. On a column with NULLs and repeats, all three differ.
Scenario"You need to join two tables on a composite key where one part, region, is often NULL on both sides. Rows are going missing. Fix it."
NULL = NULL is not true, so rows whose region is NULL never match. Compare that part null-safely: ON a.id = b.id AND a.region <=> b.region in Spark, or IS NOT DISTINCT FROM in standard SQL. Do not coalesce both sides to a placeholder unless that value can never occur for real.
Trap"WHERE NOT (amount > 100) returns every row that WHERE amount > 100 does not. True?"
No. Rows where amount is NULL fail both: amount > 100 is NULL, and NOT NULL is still NULL. The two filters together miss the NULL rows; add OR amount IS NULL to cover them.

Check yourself

4 questions

What is NULL = NULL?

Show the answer

NULL. Comparing two unknown values gives an unknown result.

What is FALSE AND NULL?

Show the answer

FALSE. AND with a false side is false whatever the other side is.

A table has amounts 10, NULL and 20. What is avg(amount)?

Show the answer

15. AVG skips the NULL: (10 + 20) / 2.

Why can WHERE id NOT IN (SELECT ref FROM t) return no rows?

Show the answer

ref contains a NULL. id <> NULL is never true, so no row passes.

Practise this

Problems that use this, graded on hidden tests

Keep going

Up next · Reading a table · lesson 3 of 3 · 6 min read
CASE WHEN and expressions
Label, bucket and clean values row by row with CASE, IF, COALESCE and arithmetic.

Related lessons

Previous: SELECT, WHERE and ORDER BY

Primary sources: NULL semantics · Built-in functions (coalesce, nullif, nvl)