Skip to content

Lesson 3 of 29Querying basics

NULL and Three-Valued Logic

Why = NULL never matches, how NOT IN can silently return nothing, and how NULL changes filters, counts, averages, sorting and constraints.

18 min read0/4 questions

Marketing asks how many customers live outside London. You write WHERE city <> 'London', get 5, and send it. The real answer is 6, because one customer has no city recorded, and your query quietly left her out. No error, no warning, just a wrong number in a slide deck. NULL causes more silent bugs than any other part of SQL, and it is a favourite topic in SQL interviews for exactly that reason. This lesson builds the mental model that makes NULL predictable: three-valued logic, then every place it changes a result.

NULL means unknown

NULL is not zero, not an empty string and not false. It is a marker that says "there is no value here", usually because the value is unknown or does not apply. Katherine Johnson's email is NULL: she may have one, we just do not have it. The CTO's manager_id is NULL: there is no such person.

Once you read NULL as "unknown", the rules follow. Is an unknown email equal to 'ada@example.com'? Unknown. Is an unknown city different from London? Also unknown: it might be London. Any comparison or arithmetic involving NULL produces NULL, because the answer depends on a value nobody knows.

Python
from shopdb import connect, showdb = connect()show(db, """SELECT NULL = NULL AS null_eq_null, NULL <> 1 AS null_ne_1, NULL + 1 AS null_plus_1, 'a' || NULL AS concat_null, NULL IS NULL AS is_null""")
Output
Press Run (⌘ Enter) to see what happens.

Even NULL = NULL is NULL. Two unknown values might be the same or might not, so the database refuses to guess. Only IS NULL gives a definite answer.

An empty string is different. '' is a known value, a string of length zero, and '' IS NULL is false in Postgres, SQLite and MySQL. Oracle is the exception: it stores an empty string as NULL, which surprises everyone who moves to or from it.

Three-valued logic

Because comparisons can return NULL, SQL logic has three truth values: TRUE, FALSE and UNKNOWN (UNKNOWN is how a NULL boolean behaves). AND, OR and NOT are extended so they still make sense:

Truth tables with UNKNOWN
TFU
TTFU
FFFF
UUFU

a AND b, with a on the rows and b on the columns. FALSE AND anything is FALSE, even FALSE AND UNKNOWN: whatever the unknown is, the result is false.

1/5

That last rule is the source of the London bug. For Margaret Hamilton, city <> 'London' is UNKNOWN, so WHERE drops her. And NOT (city = 'London') drops her too, because NOT UNKNOWN is UNKNOWN. She is in neither the London count nor the non-London count, so the two numbers do not add up to the total.

Python
from shopdb import connect, showdb = connect()show(db, "SELECT count(*) AS london FROM customers WHERE city = 'London'")show(db, "SELECT count(*) AS not_london FROM customers WHERE city <> 'London'")show(db, "SELECT count(*) AS total FROM customers")show(db, """SELECT count(*) AS not_london_fixedFROM customersWHERE city <> 'London' OR city IS NULL""")
Output
Press Run (⌘ Enter) to see what happens.

When you write a negative filter (<>, NOT, NOT IN) on a nullable column, stop and ask what should happen to the NULL rows. Then write that decision into the query.

Quick check
For a row where discount is NULL, which of these WHERE conditions keeps the row?
Need a nudge? A hint rules out a wrong answer.

IS NULL, and comparing values that may be NULL

= NULL never matches anything, so SQL gives you dedicated tests:

Python
from shopdb import connect, showdb = connect()show(db, "SELECT name FROM customers WHERE email = NULL")show(db, "SELECT name FROM customers WHERE email IS NULL")show(db, "SELECT name, email FROM customers WHERE email IS NOT NULL AND city = 'London'")
Output
Press Run (⌘ Enter) to see what happens.

The first query is a bug that looks reasonable, returns zero rows and raises no error. Many linters flag it for that reason.

Sometimes you need a comparison that treats two NULLs as equal: "has this value changed?" in an audit trigger, or matching rows from two tables where a column can be empty on both sides. a = b fails there, because NULL = NULL is UNKNOWN. The standard answer is IS DISTINCT FROM, a comparison that never returns UNKNOWN:

Python
from shopdb import connect, showdb = connect()show(db, """SELECT 1 IS DISTINCT FROM NULL AS one_vs_null, NULL IS DISTINCT FROM NULL AS null_vs_null, 2 IS NOT DISTINCT FROM 2 AS two_vs_two, 1 = NULL AS plain_equals""")
Output
Press Run (⌘ Enter) to see what happens.

IS DISTINCT FROM returns TRUE or FALSE, never NULL. In an UPDATE that only writes changed rows, WHERE old.email IS DISTINCT FROM new.email catches a change from NULL to a value, which old.email <> new.email would miss.

The NOT IN trap

This is the NULL question interviewers love, because it looks correct, it passes code review and it returns nothing. The task: list the employees who do not manage anyone.

Python
from shopdb import connect, showdb = connect()print("NOT IN:")show(db, """SELECT name FROM employeesWHERE id NOT IN (SELECT manager_id FROM employees)""")print("NOT EXISTS:")show(db, """SELECT e.name FROM employees AS eWHERE NOT EXISTS ( SELECT 1 FROM employees AS r WHERE r.manager_id = e.id)""")
Output
Press Run (⌘ Enter) to see what happens.

The subquery returns every manager_id, and that list includes NULL for the CTO and the Head of Sales. x NOT IN (1, 2, 3, NULL) expands to x <> 1 AND x <> 2 AND x <> 3 AND x <> NULL. The last part is UNKNOWN for every x, so the whole condition can never be TRUE. It is FALSE for managers and UNKNOWN for everyone else, and WHERE keeps neither.

NOT EXISTS asks a different question: "is there any row where r.manager_id = e.id?" For Mei Chen there is no such row, the NULL comparisons are simply not TRUE, and she is kept. NOT EXISTS is also what the planner optimises best (as an anti-join), so it is the right default whether or not the column is nullable today. A column that is NOT NULL today may become nullable in a migration next year, and every NOT IN against it breaks silently on that day.

If you must keep NOT IN, filter the NULLs out inside the subquery: WHERE manager_id IS NOT NULL. Note that plain IN is safe: x IN (1, NULL) is TRUE when x is 1, so a match is still found.

Predict the outputSQL

How many rows does this return on the shop data?

SELECT name FROM employees WHERE manager_id <> 1
Need a nudge? Hints walk you through it.

COALESCE and NULLIF

COALESCE(a, b, c) returns the first argument that is not NULL. It is how you choose a default at read time:

Python
from shopdb import connect, showdb = connect()show(db, """SELECT name, coalesce(email, '(no email)') AS email, coalesce(city, 'unknown') AS city, name || ' <' || coalesce(email, 'no email') || '>' AS contactFROM customersWHERE email IS NULL OR city IS NULL""")show(db, """SELECT name, stock, 1000 / NULLIF(stock, 0) AS ratioFROM productsWHERE id IN (6, 7)""")
Output
Press Run (⌘ Enter) to see what happens.

NULLIF(a, b) does the opposite: it returns NULL when a equals b, and a otherwise. Its classic use is avoiding division by zero. Dividing by NULLIF(stock, 0) turns a zero divisor into NULL, and anything divided by NULL is NULL instead of an error. A conversion-rate report that divides checkouts by visits should always do this, because one day with zero visits will otherwise fail the whole query.

Use COALESCE deliberately. Replacing NULL with 0 in a display column is fine. Replacing it before an average changes the answer, as the next section shows.

Aggregates ignore NULLs

Aggregate functions such as COUNT, SUM, AVG, MIN and MAX skip NULL inputs. The one exception is COUNT(*), which counts rows, not values.

Predict the outputPython

What does this print?

print(db.execute("""
SELECT count(*), count(email), count(DISTINCT city)
FROM customers
""").fetchone())
Need a nudge? Hints walk you through it.

The difference matters most with AVG. Here a product has four reviews, two of them without a star rating:

Python
from shopdb import connect, showdb = connect()db.executescript("""CREATE TABLE reviews ( product_id INTEGER NOT NULL REFERENCES products(id), rating INTEGER CHECK (rating BETWEEN 1 AND 5));INSERT INTO reviews VALUES (6, 5), (6, 4), (6, NULL), (6, NULL);""")show(db, """SELECT count(*) AS reviews, count(rating) AS rated, avg(rating) AS avg_rating, avg(coalesce(rating, 0)) AS avg_null_as_zero, sum(rating) AS total_starsFROM reviewsWHERE product_id = 6""")show(db, "SELECT sum(quantity) AS total, coalesce(sum(quantity), 0) AS total_or_zero FROM order_items WHERE order_id = 99")
Output
Press Run (⌘ Enter) to see what happens.

avg(rating) is 4.5: the average of the ratings that exist. avg(coalesce(rating, 0)) is 2.25, which claims the unrated reviews gave zero stars. Neither is wrong in general; they answer different questions, and you must pick the one the business means. Most people mean the first. The second quietly punishes products whose reviewers skip the stars.

The last query shows a related trap: SUM over no rows is NULL, not 0. A dashboard that shows "revenue today" will display a blank or crash a client expecting a number on a day with no orders. Wrap totals in coalesce(sum(...), 0) when zero is the right answer.

Grouping treats NULLs differently from comparison. DISTINCT, GROUP BY and UNION put all NULLs together in one group, which is why SELECT DISTINCT city returned a single NULL row in the previous lesson. NULLs are "not equal" in WHERE, but "not distinct" when grouping.

Sorting NULLs

Where should unknown values go in a sorted list? The databases disagree:

Python
from shopdb import connect, showdb = connect()show(db, "SELECT name, city FROM customers ORDER BY city LIMIT 3")show(db, "SELECT name, city FROM customers ORDER BY city NULLS LAST LIMIT 3")
Output
Press Run (⌘ Enter) to see what happens.

SQLite and MySQL treat NULL as smaller than any value, so it comes first in ascending order. Postgres and Oracle treat it as larger, so it comes last in ascending order and first in descending order. A "top 10 by price" query on a nullable column can therefore show ten NULL rows at the top on one database and real data on another.

Say what you mean with NULLS FIRST or NULLS LAST. Postgres, SQLite (3.30 and later) and Oracle support it. MySQL does not, so there you sort on an expression first: ORDER BY city IS NULL, city.

NULLs in constraints and joins

Three more places where NULL changes the rules, all of which show up in production incidents:

Python
import sqlite3from shopdb import connect, showdb = connect()db.execute("INSERT INTO customers (name, email, created_at) VALUES ('Guest One', NULL, '2025-08-01')")db.execute("INSERT INTO customers (name, email, created_at) VALUES ('Guest Two', NULL, '2025-08-01')")print("two more NULL emails accepted despite UNIQUE") db.executescript("CREATE TABLE stock_moves (qty INTEGER CHECK (qty > 0));")db.execute("INSERT INTO stock_moves VALUES (NULL)")print("NULL passed CHECK (qty > 0)") show(db, """SELECT c.name, o.id AS order_idFROM customers AS cLEFT JOIN orders AS o ON o.customer_id = c.idWHERE o.id IS NULL""")
Output
Press Run (⌘ Enter) to see what happens.
  • UNIQUE allows many NULLs. Two unknown emails are not known to be equal, so they do not conflict. That is usually what you want for an optional field. When it is not, Postgres 15 and later accept UNIQUE NULLS NOT DISTINCT, which allows at most one NULL. SQL Server is the odd one out: its unique constraints allow only one NULL by default.
  • CHECK passes on UNKNOWN. A CHECK rejects a row only when the condition is FALSE. NULL > 0 is UNKNOWN, so NULL gets in. If a value is required, the constraint you want is NOT NULL, and CHECK only constrains the values that exist. This asymmetry with WHERE (which needs TRUE) is a good interview detail.
  • Outer joins create NULLs. A LEFT JOIN keeps every customer and fills the order columns with NULL when there is no match. WHERE o.id IS NULL then finds the customers who never ordered. Filtering a left-joined column with a normal comparison, such as WHERE o.status = 'paid', throws those NULL rows away again and silently turns the outer join back into an inner one. The joins lesson covers this in depth.

The practical defence is design. Make columns NOT NULL unless "unknown" is a real state the business has, give them sensible defaults, and every query that touches them gets simpler.

Match the pairs0/5 matched

Match each expression to its result.

Choose an item, then its match on the other side.
Key terms
NULL
A marker for a missing or unknown value. Not zero, not an empty string, and not equal to anything, including itself.
three-valued logic
SQL's logic with TRUE, FALSE and UNKNOWN. Comparisons with NULL give UNKNOWN, and WHERE keeps only TRUE.
IS DISTINCT FROM
A null-safe comparison that treats two NULLs as equal and never returns UNKNOWN.
COALESCE
Returns the first non-NULL argument. Used to supply defaults when reading.
NULLIF
Returns NULL when its two arguments are equal. Used as x / NULLIF(y, 0) to avoid division by zero.
anti-join
Keeping rows from one table that have no match in another, written with NOT EXISTS or a LEFT JOIN plus IS NULL.
NULLS FIRST / NULLS LAST
ORDER BY options that place NULLs explicitly, since databases disagree on the default.