Sub topic 13
Related functions: NULLIF and DECODE
This chapter covers two functions that sit next to NVL, NVL2, and COALESCE. NULLIF produces a NULL on purpose. DECODE tests values for equality and, unlike the = operator, treats two NULLs as equal. I assume you have read the earlier chapters on three-valued logic, IS NULL, NVL, and COALESCE. I also assume you can write a CASE expression and read a WITH clause. The examples use the employees table from Oracle's HR sample schema and inline WITH data that you can paste into any Oracle 12c or later session.
NULLIF: turning a value into NULL
NULLIF(expr1, expr2) returns NULL if expr1 equals expr2. Otherwise it returns expr1. It is the mirror image of NVL: NVL replaces NULL with a value, and NULLIF replaces a value with NULL.
SELECT NULLIF(5, 5) AS same,
NULLIF(5, 6) AS different
FROM dual;The first column is NULL and the second is 5. The function behaves like this CASE expression:
CASE WHEN expr1 = expr2 THEN NULL ELSE expr1 ENDAvoiding division by zero
Dividing by zero raises ORA-01476. Dividing by NULL returns NULL, because NULL propagates through arithmetic. NULLIF(divisor, 0) converts the dangerous zero into a harmless NULL.
WITH orders (order_id, items, total) AS (
SELECT 1, 4, 100 FROM dual UNION ALL
SELECT 2, 0, 0 FROM dual UNION ALL
SELECT 3, 5, 75 FROM dual
)
SELECT order_id,
total / NULLIF(items, 0) AS price_each,
NVL(total / NULLIF(items, 0), 0) AS price_or_zero
FROM orders;Order 2 returns NULL in price_each and 0 in price_or_zero. Wrapping NULLIF in NVL is a common pairing. NULLIF creates the NULL and NVL then chooses the display value.
Cleaning sentinel values
Legacy data often stores a placeholder such as 'N/A' or -1 instead of NULL. NULLIF converts those placeholders back to NULL, so COALESCE can skip them.
WITH contacts (contact_id, mobile_phone, work_phone) AS (
SELECT 1, 'N/A', '555-0101' FROM dual UNION ALL
SELECT 2, '555-0202', 'N/A' FROM dual UNION ALL
SELECT 3, 'N/A', 'N/A' FROM dual
)
SELECT contact_id,
COALESCE(NULLIF(mobile_phone, 'N/A'),
NULLIF(work_phone, 'N/A'),
'no phone on file') AS best_phone
FROM contacts;The results are 555-0101, 555-0202, and no phone on file. Without NULLIF, COALESCE would return 'N/A' for the first row, because 'N/A' is not NULL.
Excluding values from aggregates
Aggregates ignore NULL, so NULLIF can remove unwanted values from a calculation. This is the opposite of the AVG(NVL(x, 0)) pattern from the aggregates chapter.
WITH pay (emp, bonus) AS (
SELECT 'A', 500 FROM dual UNION ALL
SELECT 'B', 0 FROM dual UNION ALL
SELECT 'C', 300 FROM dual
)
SELECT AVG(bonus) AS avg_all,
AVG(NULLIF(bonus, 0)) AS avg_nonzero
FROM pay;avg_all is about 266.67 and avg_nonzero is 400, because employee B drops out of the second average entirely.
NULLIF restrictions and gotchas
- The first argument cannot be the literal
NULL. Oracle raises an error. A column or expression that happens to be NULL at run time is fine. - If both arguments are numeric, Oracle converts the lower-precedence one. Otherwise both must have the same data type, or you get an error. Unlike NVL, NULLIF does not do broad implicit conversion between text and numbers.
- If the first argument is NULL at run time, the result is NULL, because
NULL = anythingis never true.
The empty string causes a subtle problem. Oracle treats '' as NULL, so NULLIF(col, '') compares col with NULL. That comparison is never true, and the function always returns col unchanged.
SELECT NULLIF('abc', '') AS still_abc,
TRIM(' ') AS blank_is_null
FROM dual;DECODE: equality tests where NULL matches NULL
DECODE is an Oracle-specific function that works like an if/else chain on equality.
DECODE(expr, search1, result1 [, search2, result2 ...] [, default])Oracle compares expr with each search value in order and returns the result paired with the first match. If nothing matches, it returns default. If you omit default, it returns NULL.
SELECT employee_id,
department_id,
DECODE(department_id,
10, 'Administration',
20, 'Marketing',
30, 'Purchasing',
'Other') AS dept_label
FROM employees;The NULL exception
DECODE is the one common place where Oracle treats two NULLs as equal. A search value of NULL matches an expr of NULL.
SELECT DECODE(NULL, NULL, 'equal', 'not equal') AS result FROM dual;This returns equal. WHERE NULL = NULL returns no rows, but DECODE matches. That allows a NULL test inside the function:
SELECT employee_id,
DECODE(commission_pct, NULL, 'Salary only', 'Salary + commission') AS pay_type
FROM employees;This returns the same result as the NVL2 example from earlier. The NULL search value plays the role of IS NULL.
Null-safe comparison of two columns
When you compare two nullable columns, old_val <> new_val misses rows where one side is NULL, because the comparison is unknown. DECODE gives a null-safe test.
WITH changes (id, old_val, new_val) AS (
SELECT 1, 'A', 'A' FROM dual UNION ALL
SELECT 2, NULL, NULL FROM dual UNION ALL
SELECT 3, 'A', NULL FROM dual
)
SELECT id
FROM changes
WHERE DECODE(old_val, new_val, 1, 0) = 0;The query returns only id 3, the one row that really changed. Rows 1 and 2 are equal, and row 2 is equal because NULL matches NULL. A filter of old_val <> new_val would return no rows at all here, because row 3 compares 'A' with NULL, which is unknown.
DECODE data type rules
- The return type comes from the first result value. If the first result is a character type, or is NULL, the return type is VARCHAR2.
- Oracle converts every later result to the type of the first result. A later result that cannot be converted, such as the text
'two'when the first result is a number, raises ORA-01722 at run time when that branch is chosen. - Oracle also converts
exprand the later search values to the type of the first search value. - Oracle evaluates search values in order and stops at the first match, so later search values are not evaluated.
- DECODE accepts at most 255 arguments in total.
DECODE compared with CASE
CASE is the ANSI standard and is usually the better choice for new code. A searched CASE can test ranges (WHEN salary > 10000), and it can use IS NULL. DECODE can only test equality.
The two forms handle NULL differently:
| Feature | DECODE | Simple CASE | Searched CASE |
|---|---|---|---|
| Standard SQL | No, Oracle only | Yes | Yes |
| Tests | Equality only | Equality only | Any condition |
| `NULL` matches `NULL` | Yes | No | Only with `IS NULL` |
| Range tests | No | No | Yes |
A simple CASE x WHEN NULL THEN ... never matches, because it uses = internally. Use CASE WHEN x IS NULL THEN ... instead. You will still meet DECODE in older Oracle code, so you need to read it even if you write CASE.
Choosing among the NULL functions
Each function answers a different question about NULL.
Two combinations come up often in practice:
COALESCE(NULLIF(col, sentinel), fallback)cleans placeholder data and then applies a default.NVL(numerator / NULLIF(denominator, 0), 0)makes a ratio safe and gives the result a default.
Exercise
A table readings has a numeric column value where the value -999 means "sensor failed". Write a query that returns the average of the valid readings only, ignoring failed ones. Then say why AVG(value) alone is wrong.
Show answer
SELECT AVG(NULLIF(value, -999)) AS avg_valid FROM readings; NULLIF turns -999 into NULL, and AVG ignores NULL. AVG(value) alone would include -999 in both the sum and the count, which drags the average far below the true value.
Exercise
What does SELECT DECODE(NULL, NULL, 'a', 'b') FROM dual return, and what does SELECT CASE NULL WHEN NULL THEN 'a' ELSE 'b' END FROM dual return? Explain the difference.
Show answer
The DECODE query returns 'a' and the CASE query returns 'b'. DECODE treats two NULLs as equal. A simple CASE compares with =, and NULL = NULL is unknown, so the WHEN branch is not taken and the ELSE branch runs.
Exercise
A column notes contains empty strings and strings of spaces. A colleague writes COALESCE(NULLIF(notes, ''), 'none'). It fails to replace the blank-space values. Why, and what is a better expression?
Show answer
In Oracle '' is NULL, so NULLIF(notes, '') compares notes with NULL, never matches, and returns notes unchanged. Text that is only spaces is not NULL either. Use COALESCE(TRIM(notes), 'none'), because TRIM returns NULL when nothing remains after trimming.