Sub topic 13
NVL, NVL2, COALESCE and NULLIF as shorter alternatives
CASE and DECODE can express any conditional, but many conditionals are about NULL and nothing else. Oracle has four functions for those cases. This chapter assumes you can write simple and searched CASE expressions, know that = NULL never evaluates to true, and have used DECODE. The examples use the employees table from the Oracle HR sample schema.
What the four functions do
Each function is a shorthand for a CASE expression with a fixed shape.
| Function | Meaning | Equivalent CASE |
|---|---|---|
| `NVL(a, b)` | `b` if `a` is NULL, otherwise `a` | `CASE WHEN a IS NOT NULL THEN a ELSE b END` |
| `NVL2(a, b, c)` | `b` if `a` is not NULL, otherwise `c` | `CASE WHEN a IS NOT NULL THEN b ELSE c END` |
| `COALESCE(a, b, c, ...)` | the first argument that is not NULL | `CASE WHEN a IS NOT NULL THEN a WHEN b IS NOT NULL THEN b ELSE c END` |
| `NULLIF(a, b)` | NULL if `a = b`, otherwise `a` | `CASE WHEN a = b THEN NULL ELSE a END` |
NVL: one default value
NVL(expr1, expr2) returns expr2 when expr1 is NULL. This is the most common use. A missing commission is treated as 0 so that arithmetic does not turn into NULL.
SELECT employee_id,
salary,
commission_pct,
salary * (1 + NVL(commission_pct, 0)) AS total_pay
FROM employees
WHERE department_id = 80;Without NVL, salary * (1 + NULL) is NULL, so every employee without a commission would show no total pay.
Two details matter in practice:
- NVL takes exactly two arguments. For three or more candidates, use COALESCE.
- The result type follows
expr1. Ifexpr1is a NUMBER, Oracle tries to convertexpr2to a number. Ifexpr1is character data, the result is VARCHAR2.
That second point produces a common error:
SELECT employee_id,
NVL(commission_pct, 'None') AS commission_text
FROM employees;This fails with ORA-01722: invalid number, because Oracle tries to convert 'None' to a number. Convert the number first:
SELECT employee_id,
NVL(TO_CHAR(commission_pct), 'None') AS commission_text
FROM employees;NVL2: different results for NULL and not NULL
NVL2(expr1, expr2, expr3) tests expr1 but does not return it. It returns expr2 when expr1 is not NULL and expr3 when it is NULL. Use it when the value should change in both cases.
SELECT employee_id,
NVL2(commission_pct, 'Salary + commission', 'Salary only') AS pay_type
FROM employees;NVL2 is the compact form of the DECODE NULL test from the earlier chapter. This DECODE call:
SELECT DECODE(commission_pct, NULL, 'Salary only', 'Salary + commission') AS pay_type
FROM employees;gives the same result as the NVL2 call above, and NVL2 reads in a more natural order. If expr2 and expr3 have different types, expr3 is converted to the type of expr2. Keep both branches the same type to avoid surprises.
COALESCE: the first non-NULL value
COALESCE(expr1, expr2, ..., exprN) scans its arguments from left to right and returns the first one that is not NULL. It needs at least two arguments. It returns NULL only when every argument is NULL.
SELECT employee_id,
COALESCE(phone_number, email, 'no contact') AS contact
FROM employees;COALESCE has three advantages over a chain of nested NVL calls:
- It is a standard SQL function, so the code ports to other databases. NVL, NVL2 and DECODE are Oracle-specific.
- It stops at the first non-NULL argument and does not evaluate the rest. This matters when a later argument is expensive, such as a function call or a subquery. NVL typically evaluates both of its arguments.
- It reads left to right instead of inside out.
COALESCE(a, b, c)is clearer thanNVL(a, NVL(b, c)).
Its type rules are stricter than NVL's. Mixing a NUMBER column with a string literal raises a data type error, so keep all arguments in the same type family, or convert them explicitly with TO_CHAR, TO_NUMBER or TO_DATE.
NULLIF: turn a value into NULL
NULLIF(expr1, expr2) is the reverse of NVL. It returns NULL when the two expressions are equal and expr1 when they are not. You cannot pass the literal NULL as the first argument.
The classic use is avoiding division by zero. Dividing by NULL gives NULL, while dividing by 0 raises ORA-01476: divisor is equal to zero:
SELECT 100 / NULLIF(0, 0) AS safe_ratio
FROM dual;This returns NULL instead of raising an error. The same idea works on columns:
SELECT department_id,
SUM(salary) / NULLIF(COUNT(commission_pct), 0) AS salary_per_commissioned
FROM employees
GROUP BY department_id
ORDER BY department_id;COUNT(commission_pct) counts only rows where the column is not NULL, so it is 0 for departments with no commissions. NULLIF turns that 0 into NULL and the division returns NULL for those departments.
NULLIF is also a clean way to map a placeholder value to NULL, for example NULLIF(commission_pct, 0). After that, downstream functions such as AVG ignore the placeholder rows.
Choosing between these functions and CASE
Use the shortest form that says what you mean:
- One default for NULL:
NVL, orCOALESCEif the code must run on other databases. - Different values depending on NULL or not NULL:
NVL2, which replacesDECODE(x, NULL, a, b). - Several fallback values:
COALESCE. - Mapping one specific value to NULL:
NULLIF. - Anything else, such as ranges, several different tests, or mixed result types you want to control:
CASE.
You can also combine them. This expression returns NULL for a zero commission and a text label otherwise:
SELECT employee_id,
NVL2(NULLIF(commission_pct, 0), 'Earns commission', 'No commission') AS commission_status
FROM employees;Here NULLIF first turns 0 into NULL, so employees with commission_pct of 0 get the same label as those with NULL.
Common mistakes
- Using
NVL(x, 'text')on a numeric or date column and getting ORA-01722 or a similar conversion error. Convert the first argument explicitly. - Expecting
NVL2(a, b, c)to returna. It never returnsa, onlyborc. - Passing
NULLas the first argument ofNULLIF. This raises an error. - Nesting many
NVLcalls where oneCOALESCEwould do. - Replacing NULL with 0 before an aggregate such as AVG.
AVGignores NULLs, soAVG(NVL(commission_pct, 0))averages over all rows and gives a different, usually smaller, number thanAVG(commission_pct). Decide which result you want.
Exercise
Rewrite NVL2(commission_pct, salary * commission_pct, 0) as a searched CASE expression. Then explain what NVL(salary * commission_pct, 0) returns and whether it differs from the NVL2 version.
Show answer
CASE WHEN commission_pct IS NOT NULL THEN salary * commission_pct ELSE 0 END. NVL(salary * commission_pct, 0) returns the same results. If commission_pct is NULL, the product is NULL, so NVL substitutes 0. If it is not NULL (assuming salary is not NULL), the product is returned. NVL is the shorter and clearer choice here because the not-NULL branch just returns the tested value.
Exercise
A query computes total_sales / order_count per customer and fails with ORA-01476 for customers with no orders. Fix the expression so that those customers show NULL instead of an error.
Show answer
total_sales / NULLIF(order_count, 0). NULLIF returns NULL when order_count is 0, and dividing by NULL gives NULL.
Exercise
You need the first available value among mobile_phone, office_phone and home_phone (all VARCHAR2), or the text 'none' if all are NULL. Which function do you use, and why not NVL?
Show answer
COALESCE(mobile_phone, office_phone, home_phone, 'none'). NVL accepts only two arguments, so you would have to nest several calls. COALESCE handles any number of arguments and stops at the first non-NULL value.