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.
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.
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:
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.
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.
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.
discount is NULL, which of these WHERE conditions keeps the row?IS NULL, and comparing values that may be NULL
= NULL never matches anything, so SQL gives you dedicated tests:
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:
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.
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.
How many rows does this return on the shop data?
SELECT name FROM employees WHERE manager_id <> 1
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:
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.
What does this print?
print(db.execute("""
SELECT count(*), count(email), count(DISTINCT city)
FROM customers
""").fetchone())The difference matters most with AVG. Here a product has four reviews, two of them without a star rating:
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:
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:
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
CHECKrejects a row only when the condition is FALSE.NULL > 0is UNKNOWN, so NULL gets in. If a value is required, the constraint you want isNOT NULL, andCHECKonly constrains the values that exist. This asymmetry withWHERE(which needs TRUE) is a good interview detail. - Outer joins create NULLs. A
LEFT JOINkeeps every customer and fills the order columns with NULL when there is no match.WHERE o.id IS NULLthen finds the customers who never ordered. Filtering a left-joined column with a normal comparison, such asWHERE 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 each expression to its result.
- 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.