Sub topic 2
Three-Valued Logic: TRUE, FALSE, and UNKNOWN
This chapter assumes you know basic SELECT, WHERE, JOIN, and GROUP BY, and that you understand that NULL represents a missing or inapplicable value. The key idea is that a SQL condition can produce three results: TRUE, FALSE, or UNKNOWN.
Why SQL Needs a Third Result
In ordinary logic, 5 > 2 is true and 5 > 8 is false. SQL cannot decide whether a missing value satisfies a comparison. For example, if commission is NULL, SQL cannot determine whether it is greater than 100.
commission > 100The result is UNKNOWN, not FALSE. This distinction matters because SQL filters keep only rows for which a condition is TRUE.
The same rule applies to NULL = NULL. SQL does not treat two missing values as known equal values. The result is UNKNOWN.
AND, OR, and NOT
SQL combines conditions using three-valued logic. UNKNOWN behaves differently depending on the other operand.
| AND | TRUE | FALSE | UNKNOWN |
|---|---|---|---|
| TRUE | TRUE | FALSE | UNKNOWN |
| FALSE | FALSE | FALSE | FALSE |
| UNKNOWN | UNKNOWN | FALSE | UNKNOWN |
For AND, one known FALSE is enough to produce FALSE. Otherwise, an UNKNOWN operand makes the result UNKNOWN.
| OR | TRUE | FALSE | UNKNOWN |
|---|---|---|---|
| TRUE | TRUE | TRUE | TRUE |
| FALSE | TRUE | FALSE | UNKNOWN |
| UNKNOWN | TRUE | UNKNOWN | UNKNOWN |
For OR, one known TRUE is enough to produce TRUE. If no operand is true and one is unknown, the result is UNKNOWN.
NOT reverses known results but cannot resolve an unknown result.
| Condition | `NOT` condition |
|---|---|
| TRUE | FALSE |
| FALSE | TRUE |
| UNKNOWN | UNKNOWN |
You can test these rules directly in a database that supports Boolean expressions:
SELECT
TRUE AND NULL AS true_and_unknown,
FALSE AND NULL AS false_and_unknown,
TRUE OR NULL AS true_or_unknown,
FALSE OR NULL AS false_or_unknown,
NOT NULL AS not_unknown;The results are NULL for each expression whose logical result is UNKNOWN.
How Filters Handle UNKNOWN
WHERE keeps rows only when its condition is TRUE. It removes rows where the result is either FALSE or UNKNOWN.
HAVING follows the same rule for groups. A group whose HAVING condition evaluates to UNKNOWN is excluded.
A searched CASE expression also proceeds to the next WHEN when its condition is FALSE or UNKNOWN. If no WHEN condition is true, it uses ELSE, if present.
WITH employees(name, commission) AS (
VALUES
('Ada', CAST(NULL AS DECIMAL(8,2))),
('Ben', CAST(100.00 AS DECIMAL(8,2))),
('Di', CAST(300.00 AS DECIMAL(8,2)))
)
SELECT name,
CASE
WHEN commission > 100 THEN 'above 100'
WHEN commission <= 100 THEN '100 or below'
ELSE 'unknown'
END AS category
FROM employees;Ada receives unknown because both comparisons involving her NULL commission produce UNKNOWN. Ben receives 100 or below, and Di receives above 100.
Exercise
A row has commission = NULL. What happens to the row in WHERE NOT (commission > 100)?
Show answer
The comparison produces UNKNOWN, and NOT UNKNOWN is still UNKNOWN. WHERE removes the row.