NULL & Three-Valued Logic
Understand NULL as unknown, why = NULL never matches, and why WHERE drops rows whose test is unknown.
NULL means unknown
NULL means a value is missing or unknown. It is not zero, and it is not an empty string. In our customers table, Chen and Eli have NULL for age because we do not know it.
Because a value can be unknown, a test can be unknown too. SQL logic has three results: TRUE, FALSE and unknown, which SQL writes as NULL.
A normal comparison gives NULL when either side is NULL. So 7 = NULL is NULL, and so is 7 <> NULL.
The database must not guess
If we do not know Chen's age, the honest answer to "is Chen older than 18?" is "unknown". If the database guessed, your results would quietly be wrong.
WHERE keeps a row only when the test is TRUE. Rows where the test is FALSE or unknown are both dropped.
Ask about NULL the right way
Here are three queries on customers. The comments show which customers come back:
SELECT * FROM customers WHERE age > 18; -- Asha, Dara
SELECT * FROM customers WHERE age = NULL; -- no rows, ever
SELECT * FROM customers WHERE age IS NULL; -- Chen, EliFor Chen, age > 18 is unknown, so Chen is dropped. age = NULL is unknown for every row, so nothing is kept. To test for missing values, use IS NULL or IS NOT NULL.
AND and OR follow one idea: unknown stays unknown unless the other side already decides the answer. FALSE AND NULL is FALSE. TRUE OR NULL is TRUE. TRUE AND NULL is NULL.
Watch each row get TRUE, FALSE or UNKNOWN
Pick a WHERE condition and read the result for every customer. Then open the Truth table to see how AND, OR and NOT treat NULL.
| idinteger | nametext | ageinteger | test |
|---|---|---|---|
| 1 | Asha | 31 | TRUE |
| 2 | Ben | 17 | FALSE |
| 3 | Chen | NULL | UNKNOWN |
| 4 | Dara | 24 | TRUE |
| 5 | Eli | NULL | UNKNOWN |
WHERE kept 2 of 5 rows. A row whose test is UNKNOWN is dropped, just like FALSE.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- NULL means unknown, not zero and not an empty string.
- A normal comparison with NULL gives NULL, so
= NULLnever matches. UseIS NULL. - WHERE keeps a row only when the test is TRUE, so FALSE and unknown rows are both dropped.
- Unknown stays unknown in AND, OR and NOT unless the other side already decides the answer.
Done with this concept?
Mark it complete to track your progress. No login needed.