Learning navigation

Code with Animation

NULL & Three-Valued Logic

Understand NULL as unknown, why = NULL never matches, and why WHERE drops rows whose test is unknown.

SQL6 min readConcept 3 of 44

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, Eli

For 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.

SELECT * FROM customers
WHERE age > 18;
 
-- WHERE keeps a row only
-- when the test is TRUE.
WHERE age > 18
idintegernametextageintegertest
1Asha31TRUE
2Ben17FALSE
3ChenNULLUNKNOWN
4Dara24TRUE
5EliNULLUNKNOWN

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.

  1. 1What does `age = NULL` return for each customer?
  2. 2Which query finds the customers whose age we do not know?
  3. 3Ben is 17 and Chen's age is NULL. After `WHERE NOT (age > 18)`, which customers are kept?

Remember this

  • NULL means unknown, not zero and not an empty string.
  • A normal comparison with NULL gives NULL, so = NULL never matches. Use IS 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.