Sub topic 5
CASE and NULL: Why WHEN NULL Never Matches
Assume you know basic SELECT statements, Oracle data types, and the meaning of NULL. This chapter focuses on how CASE evaluates NULL and how to write the correct test.
NULL means that a value is unknown, missing, or not applicable. It is not the same as zero, an empty string, or any other value. SQL uses three-valued logic, so a comparison can be true, false, or unknown.
Why a simple CASE does not match NULL
A simple CASE compares one expression with each WHEN value:
SELECT employee_id,
commission_pct,
CASE commission_pct
WHEN NULL THEN 'No commission'
ELSE 'Has commission'
END AS commission_status
FROM employees;The CASE expression compares commission_pct with NULL using equality logic. In SQL, the expression NULL = NULL does not produce true. It produces unknown. Therefore, the WHEN NULL branch does not match, even when commission_pct is NULL.
The ELSE branch receives those rows, so the query incorrectly labels missing commissions as Has commission.
| Expression | Result |
|---|---|
| `5 = 5` | true |
| `5 = NULL` | unknown |
| `NULL = NULL` | unknown |
A WHEN branch runs only when its comparison is true. Unknown does not count as a match.
Use a searched CASE with IS NULL
A searched CASE evaluates complete conditions. Use IS NULL when you need to identify a missing value:
SELECT employee_id,
commission_pct,
CASE
WHEN commission_pct IS NULL THEN 'No commission'
ELSE 'Has commission'
END AS commission_status
FROM employees;IS NULL is a null test. It returns true when the expression has no value. Use IS NOT NULL to test for a present value.
You can combine null tests with other conditions:
SELECT employee_id,
salary,
commission_pct,
CASE
WHEN commission_pct IS NULL THEN 'No commission'
WHEN commission_pct = 0 THEN 'Zero commission'
ELSE 'Commission available'
END AS commission_status
FROM employees;The order matters. Oracle checks the conditions from top to bottom and returns the result for the first true condition.
How NULL moves through CASE
This diagram shows the decision path for a searched CASE:
A CASE expression without an ELSE returns NULL when no condition is true:
SELECT employee_id,
CASE
WHEN commission_pct IS NULL THEN 'Missing'
END AS missing_label
FROM employees;Rows with a commission value have no matching branch, so missing_label is NULL.
Practice
Exercise
Why does CASE commission_pct WHEN NULL THEN 'Missing' ELSE 'Present' END fail to identify NULL commission values, and what should replace it?
Show answer
NULL cannot match NULL through equality. Replace it with a searched CASE using WHEN commission_pct IS NULL THEN 'Missing'.