Sub topic 5
How WHERE, HAVING, and CASE Handle UNKNOWN
Assume you know basic SELECT, WHERE, ORDER BY, JOIN, and GROUP BY. This chapter focuses on how those clauses react when a condition evaluates to UNKNOWN because it involves NULL.
`WHERE` keeps only TRUE
SQL uses three-valued logic. A condition can be TRUE, FALSE, or UNKNOWN. A comparison with NULL usually produces UNKNOWN.
For example, commission > 100 is UNKNOWN when commission is NULL. A WHERE clause keeps a row only when its condition is TRUE.
| Condition result | Kept by `WHERE` |
|---|---|
| `TRUE` | Yes |
| `FALSE` | No |
| `UNKNOWN` | No |
-- Returns only Di, whose commission is 300.00.
-- Ada and Cy produce UNKNOWN, not TRUE.
SELECT name, commission
FROM employees
WHERE commission > 100;This rule also affects compound conditions:
TRUE AND UNKNOWNisUNKNOWN.FALSE AND UNKNOWNisFALSE.TRUE OR UNKNOWNisTRUE.FALSE OR UNKNOWNisUNKNOWN.NOT UNKNOWNis stillUNKNOWN.
Therefore, adding a condition does not always make a row match in the way ordinary two-valued logic suggests.
-- The NULL commission rows still do not match.
SELECT name
FROM employees
WHERE commission > 100 OR commission = 100;For a missing commission, both comparisons are UNKNOWN, so the OR result is also UNKNOWN.
`HAVING` filters groups
HAVING filters groups after GROUP BY has formed them. Like WHERE, it keeps only groups whose condition is TRUE.
Aggregate functions often produce NULL for groups with no non-NULL input. For example, AVG(commission) is NULL when every commission in a group is missing.
SELECT manager_id,
AVG(commission) AS average_commission
FROM employees
GROUP BY manager_id
HAVING AVG(commission) > 150;A group with a NULL average is removed because NULL > 150 is UNKNOWN.
Use an explicit test when you need to keep such groups:
SELECT manager_id,
AVG(commission) AS average_commission
FROM employees
GROUP BY manager_id
HAVING AVG(commission) > 150
OR AVG(commission) IS NULL;`CASE` treats UNKNOWN as no match
A searched CASE expression checks each WHEN condition in order. It selects the first condition that is TRUE. A condition that is FALSE or UNKNOWN is skipped.
SELECT name,
CASE
WHEN commission >= 200 THEN 'high'
WHEN commission IS NULL THEN 'missing'
ELSE 'standard'
END AS commission_status
FROM employees;The IS NULL branch must appear if missing values need their own label. Without it, a NULL commission reaches ELSE.
A simple CASE compares values, so it also cannot match NULL with =:
SELECT name,
CASE commission
WHEN 100 THEN 'fixed'
WHEN NULL THEN 'missing' -- never matches
ELSE 'other'
END AS category
FROM employees;Use a searched CASE with IS NULL for that requirement.
Exercise
Why does WHERE commission <> 100 exclude employees whose commission is NULL, and how can a query include them?
Show answer
NULL <> 100 is UNKNOWN, and WHERE keeps only TRUE. Use WHERE commission <> 100 OR commission IS NULL.