Sub topic 2
CASE and NULL: why WHEN NULL never matches
This chapter assumes you can write SELECT statements with WHERE and ORDER BY, know the Oracle types NUMBER and VARCHAR2, and understand that NULL means "no value is known." The examples use the standard HR employees table.
Why WHEN NULL fails
A comparison with NULL returns UNKNOWN, not TRUE. A simple CASE tests equality, so WHEN NULL never returns TRUE, even for rows where the tested value is NULL.
SELECT employee_id,
commission_pct,
CASE commission_pct
WHEN NULL THEN 'No commission'
ELSE 'Has commission'
END AS wrong_result
FROM employees;Every row returns 'Has commission'. Use a searched CASE with IS NULL instead:
SELECT employee_id,
commission_pct,
CASE
WHEN commission_pct IS NULL THEN 'No commission'
ELSE 'Has commission'
END AS correct_result
FROM employees;> Note: Keep the ELSE branch. Without it, a CASE that matches nothing returns NULL.
DECODE: Oracle's compact value-matching function
DECODE takes an expression, then pairs of search and result values, then an optional default. It compares the expression with each search value in order and returns the matching result. If nothing matches and no default is given, it returns NULL. DECODE is specific to Oracle, so use CASE when the SQL must run on other databases.
SELECT employee_id,
department_id,
DECODE(department_id, 10, 'Administration', 20, 'Marketing', 'Other') AS dept_label
FROM employees;DECODE treats two NULLs as equal
DECODE treats a NULL expression as matching a NULL search value. This gives the answer the first query was trying to get:
SELECT employee_id,
commission_pct,
DECODE(commission_pct, NULL, 'No commission', 'Has commission') AS decode_result
FROM employees;This difference from CASE is easy to miss when you move code between the two forms.
Choosing between CASE and DECODE, and rewriting DECODE as CASE
Use CASE for portable SQL, for range tests, and for any condition beyond equality. Use DECODE only for short equality lookups in Oracle code. To rewrite DECODE as CASE, turn each search and result pair into a WHEN branch. A NULL search value must become an IS NULL test.
| DECODE form | Equivalent CASE |
|---|---|
| DECODE(department_id, 10, 'Admin', 'Other') | CASE department_id WHEN 10 THEN 'Admin' ELSE 'Other' END |
| DECODE(commission_pct, NULL, 'None', 'Some') | CASE WHEN commission_pct IS NULL THEN 'None' ELSE 'Some' END |
Exercise
Does CASE commissionpct WHEN NULL THEN 'x' ELSE 'y' END return 'x' for rows where commissionpct is NULL?
Show answer
No. The WHEN NULL test never returns TRUE, so every row returns 'y'. Use WHEN commission_pct IS NULL to match NULL values.