Sub topic 16
NULLs and Three-Valued Logic
Prerequisites and the meaning of NULL
Assume you know basic SQL SELECT, comparison operators, and Boolean logic. This chapter focuses on how SQL handles missing or unknown values.
NULL is a special marker meaning that a value is missing, unknown, or not applicable. It is not zero, an empty string, or the Boolean value FALSE.
SQL comparisons involving NULL usually produce UNKNOWN:
SELECT NULL = 5; -- UNKNOWN
SELECT NULL <> 5; -- UNKNOWN
SELECT NULL = NULL; -- UNKNOWNSQL therefore uses three-valued logic. A condition can be TRUE, FALSE, or UNKNOWN.
Three-valued logic
The important truth tables are:
| A | NOT A |
|---|---|
| TRUE | FALSE |
| FALSE | TRUE |
| UNKNOWN | UNKNOWN |
For AND, one FALSE operand makes the result FALSE. For OR, one TRUE operand makes the result TRUE.
| A | B | A AND B | A OR B |
|---|---|---|---|
| TRUE | UNKNOWN | UNKNOWN | TRUE |
| FALSE | UNKNOWN | FALSE | UNKNOWN |
| UNKNOWN | UNKNOWN | UNKNOWN | UNKNOWN |
A WHERE clause keeps only rows for which its condition is TRUE. Both FALSE and UNKNOWN remove the row.
-- Suppose Student contains ages 18, 21, and NULL.
SELECT * FROM Student
WHERE age > 20; -- keeps age 21
SELECT * FROM Student
WHERE NOT (age > 20); -- keeps age 18, not the NULL ageThe row with NULL does not satisfy either condition because both age > 20 and its negation are UNKNOWN.
Testing and handling NULL
Use IS NULL and IS NOT NULL, never = NULL or <> NULL.
SELECT *
FROM Student
WHERE age IS NULL;
SELECT *
FROM Student
WHERE age IS NOT NULL;Arithmetic with NULL generally produces NULL. Aggregate functions also need care:
SELECT COUNT(*) FROM Student; -- counts every row
SELECT COUNT(age) FROM Student; -- skips NULL agesSUM, AVG, MIN, and MAX ignore NULL inputs. If every input is NULL, these functions usually return NULL.
-- NOT EXISTS is safe when Enrolled.sid may contain NULL.
SELECT s.sid
FROM Student AS s
WHERE NOT EXISTS (
SELECT 1
FROM Enrolled AS e
WHERE e.sid = s.sid
);Exam strategy
When solving a GATE question, mark every NULL, evaluate comparisons as UNKNOWN, and apply the rule that WHERE retains only TRUE.
Exercise
A table T contains three rows with x values 5, 10, and NULL. How many rows are returned by SELECT * FROM T WHERE x <> 10?
Show answer
One row. The value 5 makes the condition TRUE. The value 10 makes it FALSE, and NULL makes it UNKNOWN; both FALSE and UNKNOWN are discarded.