Sub topic 5
How WHERE, HAVING, and CASE Handle UNKNOWN
This chapter assumes you know basic SELECT, WHERE, GROUP BY, and JOINs. It also assumes you have met three-valued logic, where a condition evaluates to TRUE, FALSE, or UNKNOWN, and that any comparison with NULL yields UNKNOWN. Here you will see what each clause does with an UNKNOWN result. The rules differ slightly between clauses, and most NULL bugs come from those differences.
All examples use the employees table from the earlier chapters: Ada (no manager, no commission), Ben (manager 1, commission 100), Cy (manager 1, no commission), and Di (manager 2, commission 300).
The core rule: only TRUE passes
A filtering clause evaluates its condition for each row, or for each group in the case of HAVING. It keeps the row only when the result is TRUE. FALSE and UNKNOWN are both discarded, and the clause does not tell the two apart.
This is why the three-valued model matters. A query can discard rows that are not FALSE, and you will not see an error or a warning.
WHERE: a condition and its negation do not cover every row
If a condition keeps some rows, you might expect its negation to keep all the others. With NULLs it does not.
-- Returns Di.
SELECT name FROM employees WHERE commission > 100;
-- Returns Ben. Ada and Cy are missing here too.
SELECT name FROM employees WHERE NOT (commission > 100);For Ada and Cy, commission > 100 is UNKNOWN, and NOT UNKNOWN is still UNKNOWN. Neither query returns them. The two result sets together contain only three of the four employees.
The same logic applies to AND and OR. The result can still be decided when one side is UNKNOWN:
| Expression | Result |
|---|---|
| UNKNOWN AND TRUE | UNKNOWN |
| UNKNOWN AND FALSE | FALSE |
| UNKNOWN OR TRUE | TRUE |
| UNKNOWN OR FALSE | UNKNOWN |
| NOT UNKNOWN | UNKNOWN |
Here is the OR case in practice:
-- Returns Ada and Di.
SELECT name
FROM employees
WHERE commission > 100 OR name = 'Ada';Ada's row evaluates to UNKNOWN OR TRUE, which is TRUE. Cy's row evaluates to UNKNOWN OR FALSE, which is UNKNOWN, so it is dropped.
To handle NULL rows deliberately, say so in the condition:
-- Returns Ada, Cy, and Di.
SELECT name
FROM employees
WHERE commission > 100 OR commission IS NULL;Some systems also let you test the truth value directly with IS TRUE, IS NOT TRUE, and IS UNKNOWN. IS NOT TRUE is true for both FALSE and UNKNOWN, so it is the exact complement of the WHERE rule:
-- PostgreSQL and MySQL. Returns Ada, Ben, and Cy.
SELECT name FROM employees WHERE (commission > 100) IS NOT TRUE;HAVING: the same rule, applied to groups
HAVING filters groups after aggregation, and it uses the same rule: a group stays only when its condition is TRUE. The usual source of UNKNOWN is an aggregate that returns NULL. SUM, AVG, MIN, and MAX return NULL when every input value in the group is NULL, or when the group has no non-NULL inputs.
SELECT manager_id,
COUNT(*) AS reports,
AVG(commission) AS avg_commission
FROM employees
GROUP BY manager_id
HAVING AVG(commission) > 50;The groups are:
| manager_id | Rows | AVG(commission) | `> 50` |
|---|---|---|---|
| NULL | Ada | NULL | UNKNOWN |
| 1 | Ben, Cy | 100.00 | TRUE |
| 2 | Di | 300.00 | TRUE |
The query returns managers 1 and 2. The group for Ada exists and contains a row, but its average is NULL, so the group vanishes without a trace. You can handle it the same way as in WHERE:
-- Returns the NULL group and manager 1.
SELECT manager_id, AVG(commission) AS avg_commission
FROM employees
GROUP BY manager_id
HAVING COALESCE(AVG(commission), 0) < 150;Here the NULL group's average becomes 0, which is less than 150, so it is kept. Without the COALESCE, AVG(commission) < 150 would return only manager 1.
Notice also that GROUP BY puts all NULL manager_id values into one group. That is a grouping rule, not a comparison, and a later chapter covers it.
CASE: UNKNOWN means "try the next branch"
A searched CASE expression tests each WHEN condition in order and returns the result for the first condition that is TRUE. An UNKNOWN condition does not match, so evaluation moves on. If no branch matches and there is no ELSE, CASE returns NULL.
SELECT name,
CASE
WHEN commission > 100 THEN 'high'
WHEN commission <= 100 THEN 'low'
ELSE 'none'
END AS band
FROM employees;The results are:
| name | band |
|---|---|
| Ada | none |
| Ben | low |
| Cy | none |
| Di | high |
For Ada and Cy both WHEN conditions are UNKNOWN, so the ELSE branch runs. The label 'none' happens to be correct here. In other queries the ELSE branch silently absorbs NULL rows that you never intended to treat the same as FALSE rows, so name the NULL case explicitly:
SELECT name,
CASE
WHEN commission IS NULL THEN 'no commission recorded'
WHEN commission > 100 THEN 'high'
ELSE 'low'
END AS band
FROM employees;Order matters. The IS NULL test comes first so that the later comparisons only ever see non-NULL values.
The simple CASE form cannot match NULL
The simple form, CASE expr WHEN value THEN ..., compares with =. A comparison with NULL is UNKNOWN, so a WHEN NULL branch never fires:
-- Returns 'has value' for every row, including Ada and Cy.
SELECT name,
CASE commission
WHEN NULL THEN 'none'
ELSE 'has value'
END AS status
FROM employees;Use the searched form with IS NULL instead:
SELECT name,
CASE WHEN commission IS NULL THEN 'none' ELSE 'has value' END AS status
FROM employees;Clauses compared
Each clause treats UNKNOWN as "not a match", with one important exception:
| Clause | Row, group, or branch is accepted when the condition is | UNKNOWN is treated as |
|---|---|---|
| WHERE | TRUE | rejected |
| HAVING | TRUE | rejected |
| JOIN ... ON | TRUE | not a match (outer joins then add NULL-extended rows) |
| CASE WHEN | TRUE | try the next branch |
| CHECK constraint | TRUE or UNKNOWN | accepted |
The CHECK constraint is the exception. A CHECK (commission >= 0) constraint accepts a row with a NULL commission, because the standard only rejects a row when the condition is FALSE. If you want to forbid NULL, add NOT NULL as well. The constraints chapter returns to this.
Common errors
- Writing
= NULLor<> NULLin any clause. The result is always UNKNOWN, so WHERE and HAVING return nothing, and CASE never takes that branch. - Assuming
NOTflips the row set.NOT (x > 5)andx > 5can both exclude the same NULL row. - Letting ELSE hide NULLs. A catch-all ELSE puts NULL rows in the same bucket as rows you meant to match, such as FALSE results.
- Filtering on an aggregate that may be NULL. An all-NULL group disappears from HAVING output.
- Using
WHEN NULLin a simple CASE. It never matches.
A fast debugging method is to move the condition into the SELECT list and look at its value row by row. Some systems, such as PostgreSQL, display the UNKNOWN result as NULL:
SELECT name, commission, (commission > 100) AS test_result
FROM employees;Ada and Cy show a NULL test_result, which tells you they were never FALSE. They were UNKNOWN, and a filter dropped them.
Exercise
The query SELECT name FROM employees WHERE commission <> 300 AND manager_id <> 1; is run on the sample table. Which rows does it return? Then change it so it also returns employees whose commission or manager_id is NULL but who would otherwise satisfy the intent.
Show answer
It returns no rows. Ada: commission <> 300 is UNKNOWN and manager_id <> 1 is UNKNOWN, so the result is UNKNOWN. Ben: 100 <> 300 is TRUE but 1 <> 1 is FALSE, so the result is FALSE. Cy: commission <> 300 is UNKNOWN and manager_id <> 1 is FALSE, so UNKNOWN AND FALSE is FALSE. Di: 300 <> 300 is FALSE, so the result is FALSE. A NULL-safe version uses IS DISTINCT FROM: WHERE commission IS DISTINCT FROM 300 AND manager_id IS DISTINCT FROM 1. This returns Ada only (her commission is NULL, so it is distinct from 300, and her managerid is NULL, so it is distinct from 1). Cy is excluded because his managerid is 1.
Exercise
A report uses CASE status WHEN NULL THEN 'unknown' WHEN 'A' THEN 'active' ELSE 'other' END. Rows with a NULL status are labelled 'other'. Explain why, and write a corrected version.
Show answer
The simple CASE compares status = NULL, which is UNKNOWN for every row, so the first branch never fires. A NULL status also fails status = 'A', so it reaches ELSE. The corrected version uses the searched form: CASE WHEN status IS NULL THEN 'unknown' WHEN status = 'A' THEN 'active' ELSE 'other' END.
Exercise
A query groups employees by manager_id and uses HAVING MAX(commission) < 200. Which groups survive on the sample table, and why is the group for Ada missing?
Show answer
Only manager 1 survives, because MAX(commission) for Ben and Cy is 100, which is less than 200. Manager 2 has a maximum of 300, so its condition is FALSE. The NULL manager_id group holds only Ada, whose commission is NULL, so MAX returns NULL. NULL < 200 is UNKNOWN, and HAVING keeps only TRUE.