Sub topic 6
Branching on NULL with NVL2
This chapter assumes you can write SELECT statements with WHERE and column aliases, and that you know the basic Oracle data types (NUMBER, VARCHAR2, DATE). It also assumes you have met NVL, which replaces a NULL with a default value. The examples use the employees table from Oracle's sample HR schema, plus dual for quick experiments.
What NVL2 does
NVL2 is a built-in Oracle function that takes three arguments and picks one of two results. Which one it picks depends on whether the first argument is NULL.
NVL2(expr1, expr2, expr3)- If
expr1is not NULL, NVL2 returnsexpr2. - If
expr1is NULL, NVL2 returnsexpr3.
NVL gives you a default for a missing value. NVL2 lets you choose a different result for each case, and neither result has to be the tested value itself.
SELECT employee_id,
NVL2(commission_pct, 'Salary + commission', 'Salary only') AS pay_type
FROM employees;Employees with a commission_pct get Salary + commission. Employees whose commission_pct is NULL get Salary only. The query never displays the commission value. It only uses it to decide which label to show.
Testing NULL-ness, not the value
NVL2 only asks whether expr1 is NULL. It does not look at what the value is. This matters with numbers, where zero is a real value and not a missing one.
Suppose an employee has commission_pct = 0. That value is not NULL, so NVL2 returns expr2:
SELECT NVL2(0, 'has a value', 'is null') AS zero_test,
NVL2('', 'has a value', 'is null') AS empty_string_test
FROM dual;The first column is has a value. The second is is null, because Oracle treats the empty string as NULL (covered earlier in this tutorial). If your data uses 0 or a blank string to mean "none", NVL2 will not treat it as missing. Use CASE or NULLIF for those rules.
Using different expressions in each branch
The main reason to choose NVL2 over NVL is that expr2 can be any expression, usually one built from expr1. This computes total pay and handles the NULL case in one step:
SELECT employee_id,
salary,
commission_pct,
NVL2(commission_pct,
salary + salary * commission_pct,
salary) AS total_pay
FROM employees;This gives the same answer as salary + salary * NVL(commission_pct, 0). Here NVL is shorter, so prefer it. NVL2 pays off when the two branches are shaped differently. This query builds a sentence from a column that may be NULL:
SELECT first_name || ' ' || last_name
|| NVL2(manager_id,
' reports to employee ' || manager_id,
' is at the top of the hierarchy') AS description
FROM employees;Only one branch is built for each row. Using NVL here would be awkward, because the text you want when manager_id is present is not the manager_id itself.
The relationship with NVL
NVL2 can imitate NVL. These two expressions return the same result:
SELECT NVL(commission_pct, 0) AS with_nvl,
NVL2(commission_pct, commission_pct, 0) AS with_nvl2
FROM employees;The reverse does not hold. NVL returns expr1 itself when it is not NULL, so it cannot return a different value for the non-NULL case. Use NVL when you want the original value or a default. Use NVL2 when the non-NULL case needs its own result.
| Function | Arguments | Non-NULL case returns | NULL case returns |
|---|---|---|---|
| `NVL(a, b)` | 2 | `a` | `b` |
| `NVL2(a, b, c)` | 3 | `b` | `c` |
Turning NULL-ness into a flag
A common use is converting "has a value or not" into 1 or 0. Summing that flag counts the rows that have a value:
SELECT COUNT(*) AS total_employees,
SUM(NVL2(commission_pct, 1, 0)) AS with_commission,
SUM(NVL2(commission_pct, 0, 1)) AS without_commission
FROM employees;SUM(NVL2(commission_pct, 1, 0)) gives the same number as COUNT(commission_pct), because COUNT on a column skips NULLs. The NVL2 form becomes useful when you want several conditional counts side by side in one pass over the table, as above.
You can also total a column for only some rows:
SELECT SUM(NVL2(commission_pct, salary, 0)) AS salary_of_commissioned_staff
FROM employees;Each row adds its salary if it has a commission, and 0 if it does not.
NVL2 compared with CASE
Every NVL2 call can be rewritten as a CASE expression:
SELECT employee_id,
CASE
WHEN commission_pct IS NOT NULL THEN 'Salary + commission'
ELSE 'Salary only'
END AS pay_type
FROM employees;This returns the same result as the NVL2 query at the start of the chapter. The differences:
- NVL2 is shorter when the only test is "is it NULL".
CASEis part of the SQL standard and works on other databases. NVL2 is an Oracle function.CASEcan test other conditions (commission_pct > 0.2, a range, a combination of columns). NVL2 can only test NULL-ness.
If you expect the query to grow extra conditions later, start with CASE.
Data types of the result
NVL2 returns one value, so Oracle has to decide on a single data type for the result. The rules depend on expr2:
expr1can be of any data type.expr2andexpr3can be of any data type except LONG.- If
expr2is character data, Oracle convertsexpr3to a character type and returns VARCHAR2. - If
expr2is numeric, Oracle converts the other argument to the numeric type with higher precedence and returns that type.
This means the order of the two result arguments matters. The next two queries look similar, but only one works:
-- Works: expr2 is text, so the number 0 becomes the text '0'
SELECT NVL2(commission_pct, 'has commission', 0) AS result
FROM employees;
-- Raises ORA-01722: expr2 is numeric, so 'none' must become a number
SELECT NVL2(commission_pct, 1, 'none') AS result
FROM employees;The first query succeeds, but mixing types like this is a habit to avoid. The 0 is silently turned into '0', and later code may not expect that. It is better to make the types match yourself:
SELECT NVL2(commission_pct,
TO_CHAR(commission_pct, 'FM0.00'),
'none') AS commission
FROM employees;Both branches now return text, and the result type is clear.
NVL2 with literal NULLs
Because the first argument only has to be "something that may be NULL", you can test expressions, not just columns:
SELECT NVL2(NULL, 'not null', 'null') AS literal_null,
NVL2(1 / 2, 'not null', 'null') AS expression,
NVL2(NULLIF('A', 'A'), 'differs', 'same') AS with_nullif
FROM dual;The results are null, not null, and same. NULLIF('A', 'A') returns NULL when its two arguments are equal, so NVL2 reads it as "no difference found". NULLIF is covered in a later chapter.
Common mistakes
- Expecting NVL2 to return the tested value.
NVL2(a, b, c)returnsborc, nevera. If you wantawhen it exists, writeNVL(a, c). - Swapping the second and third arguments. The second argument is for the not NULL case. The first time you use NVL2, read it aloud: "if expr1 has a value, give me expr2, otherwise expr3".
- Treating 0 or a blank as NULL. NVL2 treats
0and' '(a space) as values. Only a true NULL, including the empty string'', takes the third argument. - Mixing result types. Make
expr2andexpr3the same type, usingTO_CHAR,TO_NUMBER, orTO_DATEif needed. - Nesting NVL2 deeply. Three or more levels of NVL2 are hard to read. Use
CASE, or COALESCE if you are just taking the first available value.
Summary
NVL2(expr1, expr2, expr3)returnsexpr2whenexpr1is not NULL andexpr3when it is NULL.- It tests NULL-ness only.
0and a space count as values, and''counts as NULL. - It is the right tool when the non-NULL case needs a different result than the tested value, such as labels, alternate formulas, and 1/0 flags.
- The result type is set by
expr2, so match the types of the two result arguments explicitly. CASEis the portable alternative and handles conditions beyond NULL tests.
Exercise
Write a query on the employees table that returns employee_id and a column bonus_note. The note should be 'Eligible: ' || (commission_pct * 100) || '%' for employees who have a commission_pct, and 'Not eligible' for the others. Then rewrite the logic as a CASE expression.
Show answer
With NVL2: SELECT employeeid, NVL2(commissionpct, 'Eligible: ' || (commissionpct * 100) || '%', 'Not eligible') AS bonusnote FROM employees; With CASE: SELECT employeeid, CASE WHEN commissionpct IS NOT NULL THEN 'Eligible: ' || (commissionpct * 100) || '%' ELSE 'Not eligible' END AS bonusnote FROM employees; Both branches return text, so there is no type conflict. The number is converted to text by the concatenation.
Exercise
What does this query return, and why does the second column raise an error or not? SELECT NVL2(NULL, 1, 2) AS a, NVL2('x', 1, 'none') AS b FROM dual;
Show answer
Column a is 2, because the first argument is NULL, so NVL2 returns the third argument. Column b raises ORA-01722. The first argument 'x' is not NULL, so Oracle would return 1, but because expr2 is numeric the third argument 'none' must be converted to a number, and that conversion fails. The error is raised even though the 'none' branch is not the one chosen. Fix it by making both branches the same type, for example NVL2('x', '1', 'none').