Sub topic 7
DECODE Treats Two NULLs as Equal
Prerequisites
This chapter assumes that you can write basic SELECT statements and understand that NULL means a missing or unknown value. In Oracle, comparing NULL with = does not produce TRUE. It produces UNKNOWN.
DECODE is an Oracle SQL function that compares one expression with a list of search values. Its special rule is that it considers two NULL values equal.
The NULL difference between DECODE and CASE
A simple CASE compares an expression with each WHEN value:
SELECT CASE NULL
WHEN NULL THEN 'Matched'
ELSE 'Not matched'
END AS case_result
FROM dual;The result is Not matched. The comparison is effectively:
NULL = NULLThat comparison is not true in SQL. Therefore, WHEN NULL does not match.
DECODE handles this situation differently:
SELECT DECODE(NULL,
NULL, 'Matched',
'Not matched') AS decode_result
FROM dual;The result is Matched. When the expression and a search value are both NULL, DECODE treats them as equal.
The evaluation works like this:
The equivalent CASE expression
To express the same logic with CASE, use a searched CASE. A searched CASE tests complete conditions rather than comparing one expression automatically.
SELECT CASE
WHEN NULL IS NULL THEN 'Matched'
ELSE 'Not matched'
END AS case_result
FROM dual;For a column, use IS NULL explicitly:
SELECT employee_id,
commission_pct,
DECODE(commission_pct,
NULL, 'No commission',
'Has commission') AS decode_result,
CASE
WHEN commission_pct IS NULL THEN 'No commission'
ELSE 'Has commission'
END AS case_result
FROM employees;Both expressions classify a missing commission as No commission. The searched CASE is usually clearer when the condition is more complicated than equality.
| Requirement | DECODE | Equivalent CASE |
|---|---|---|
| Match a `NULL` expression | `DECODE(value, NULL, result, default)` | `CASE WHEN value IS NULL THEN result ELSE default END` |
| Match a non-NULL value | Equality search | Equality or any searched condition |
| Match two `NULL` values | Yes | Only with `IS NULL` |
Important Oracle detail
Oracle treats a zero-length character string such as '' as NULL in SQL. Consequently, this expression matches:
SELECT DECODE('', NULL, 'Same', 'Different') AS result
FROM dual;The result is Same. This rule applies to character values and can surprise developers coming from databases where an empty string and NULL are distinct.
Exercise
Exercise
Rewrite DECODE(commission_pct, NULL, 'Missing', 'Present') as an equivalent searched CASE expression.
Show answer
CASE WHEN commission_pct IS NULL THEN 'Missing' ELSE 'Present' END