Sub topic 10
NVL, NVL2, or COALESCE: choosing the right one
The three functions overlap, so a query can often be written with any of them. This chapter explains how they differ and gives you rules for picking one. It assumes you can already use each function on its own, and that you know Oracle's data types and NULL propagation. It also assumes you have run basic queries against dual, employees, and a contacts table like the one used earlier in this tutorial.
The three functions side by side
| Feature | NVL | NVL2 | COALESCE |
|---|---|---|---|
| Arguments | Exactly 2 | Exactly 3 | 2 or more |
| Question it answers | "If this is NULL, what instead?" | "Is this NULL? Give me one value or the other." | "What is the first non-NULL value in this list?" |
| Return value when the first argument is not NULL | The first argument | The second argument | The first argument |
| Return value when the first argument is NULL | The second argument | The third argument | The next non-NULL argument, or NULL |
| Standard | Oracle-specific | Oracle-specific | ANSI SQL |
| Evaluation | Evaluates both arguments | Branch function | Stops at the first non-NULL |
The main difference is what each one does with the non-NULL value. NVL and COALESCE return it. NVL2 throws it away and returns a different value. Use NVL2 when you want to react to the NULL-ness of a column and don't need its value.
Choosing by shape of the problem
The shape of the problem usually decides which function to use.
One column, one default: NVL
For a single default, NVL is short and well understood.
SELECT employee_id,
salary + salary * NVL(commission_pct, 0) AS total_pay
FROM employees;Different output for NULL and non-NULL: NVL2
NVL2 is for labeling or switching on whether a value exists.
SELECT employee_id,
NVL2(commission_pct, 'Salary + commission', 'Salary only') AS pay_type
FROM employees;You could write this with NVL, but you would have to compare against a sentinel value, and that is fragile. The equivalent CASE expression is longer.
SELECT employee_id,
CASE WHEN commission_pct IS NOT NULL
THEN 'Salary + commission'
ELSE 'Salary only'
END AS pay_type
FROM employees;Prefer NVL2 for a simple two-way split on NULL. Prefer CASE when you need more conditions than NULL versus not NULL.
A frequent mistake is using NVL2 as if it were NVL. NVL2(commission_pct, 0) fails with a "not enough arguments" error. NVL2(commission_pct, commission_pct, 0) works, but NVL(commission_pct, 0) says the same thing more clearly.
A list of fallbacks: COALESCE
With several candidate columns, nesting NVL calls gets hard to read.
-- Nested NVL: harder to scan and to extend
SELECT contact_id,
NVL(mobile_phone, NVL(work_phone, NVL(home_phone, 'no phone on file'))) AS best_phone
FROM contacts;
-- COALESCE: one flat list
SELECT contact_id,
COALESCE(mobile_phone, work_phone, home_phone, 'no phone on file') AS best_phone
FROM contacts;Both queries return the same result. The flat list makes the priority order obvious, and adding a fourth phone column is a one-word change.
Data type handling
The two functions treat mismatched types differently, and this explains many unexpected errors.
NVL converts the second argument implicitly to match the first. If the first argument is a character type, the result is VARCHAR2. If the first argument is numeric, Oracle works out a numeric result type, and a text replacement that is not a number fails during conversion.
COALESCE is stricter. Oracle expects all the expressions to share a data type family, and a mismatch is reported as an inconsistent data type error. In practice this means COALESCE refuses to quietly convert a string literal into a number.
-- NVL: fails with ORA-01722 because 'none' is not a number
SELECT NVL(commission_pct, 'none') FROM employees;
-- COALESCE: also fails, with a data type error (often ORA-00932)
SELECT COALESCE(commission_pct, 'none') FROM employees;
-- Both work once the column is converted to text
SELECT NVL(TO_CHAR(commission_pct), 'none') AS commission_nvl,
COALESCE(TO_CHAR(commission_pct), 'none') AS commission_coalesce
FROM employees;The strictness of COALESCE is useful in one respect. It fails the same way for every row, so you see the error as soon as you run the query. NVL's implicit conversion can work for most values and then fail on an unusual one. For example, NVL(varchar_col, 0) works only while the column's values can be converted to a number, and the failure appears when a row with 'abc' is read.
For NVL2, the data type comes from the second argument. The type of the first argument does not matter, since only its NULL-ness is tested. The third argument is converted to match the second.
Evaluation behavior
NVL evaluates both of its arguments, even when the first one is not NULL. COALESCE evaluates its arguments from left to right and stops at the first non-NULL one.
This only matters when the fallback is expensive or has side effects. The following function reports each time it runs.
SET SERVEROUTPUT ON
CREATE OR REPLACE FUNCTION slow_default RETURN NUMBER IS
BEGIN
DBMS_OUTPUT.PUT_LINE('slow_default was called');
RETURN 0;
END;
/
SELECT NVL(1, slow_default()) AS nvl_result FROM dual;
SELECT COALESCE(1, slow_default()) AS coalesce_result FROM dual;The first query prints the message because NVL evaluates its second argument. The second query does not, because COALESCE finds 1 and stops. Both queries return 1.
For a cheap constant such as 0, the difference is not measurable. It matters in three cases:
- The fallback is a scalar subquery against a large table.
- The fallback is a PL/SQL function that does real work.
- The fallback can raise an error, such as a division by zero, that you want to avoid when the first value is present.
In those cases use COALESCE, or use a CASE expression, which also evaluates only the branch it needs.
Portability and maintenance
COALESCE is part of the ANSI SQL standard. It works on other databases, so code that uses it moves with fewer changes. NVL and NVL2 are Oracle-specific. If your SQL has to run on more than one database, or if you expect to migrate, prefer COALESCE and CASE.
Inside an Oracle-only code base, NVL is so common that most Oracle developers read it instantly. A team convention matters more here than the choice itself. Pick one for the simple two-argument case and use it consistently.
Putting it together: a worked comparison
The table below applies the rules to common tasks.
| Task | Best choice | Why |
|---|---|---|
| Treat a missing commission as 0 in arithmetic | NVL | One column, one default |
| Label rows as "has commission" or "no commission" | NVL2 | The original value is not needed |
| Use mobile, then work, then home phone | COALESCE | More than two candidates |
| Fall back to a value that comes from a slow subquery | COALESCE | Skips the fallback when it is not needed |
| Query must run on Oracle and another database | COALESCE or CASE | ANSI standard |
| Different output for three or more conditions | CASE | NULL-ness is only one of the conditions |
A combined example uses two functions for two different jobs. NVL2 picks the label, and COALESCE picks the contact value.
SELECT contact_id,
NVL2(mobile_phone, 'Mobile', 'Other') AS preferred_type,
COALESCE(mobile_phone, work_phone, home_phone, 'no phone on file') AS best_phone
FROM contacts;Common mistakes
- Using
= NULLinside the function. These functions replace NULL values. They do not change how comparisons work, so keep usingIS NULLin WHERE clauses. - Replacing NULL with a value that has meaning.
NVL(salary, 0)makes a missing salary look like an unpaid employee. Report NULL as NULL when the distinction matters. - Wrapping a column in NVL in a WHERE clause.
WHERE NVL(commission_pct, 0) = 0cannot use a normal index oncommission_pct. Rewrite it asWHERE commission_pct IS NULL OR commission_pct = 0when the index matters. - Assuming the result length. When you mix a short column with a long literal, check that the result still fits the place you store it.
Summary of the rules
- Need one default for one expression, in Oracle only: use NVL.
- Need one result when a value is present and a different one when it is missing: use NVL2.
- Need the first available value from several: use COALESCE.
- Need ANSI portability, or the fallback is costly or risky: use COALESCE.
- Always make the data types match yourself instead of relying on conversion.
Exercise
A report must show each employee's bonus text. If commission_pct is present, show it as text such as 0.2. If it is missing, show none. Which function would you use, and why? Write the query.
Show answer
Use NVL (or COALESCE), because the original value must be returned when it is not NULL. NVL2 would also work with NVL2(commission_pct, TO_CHAR(commission_pct), 'none'), but it is more verbose. The key point is converting the number to text first, because mixing a number and the string 'none' would raise an error:
SELECT employeeid,
NVL(TOCHAR(commissionpct), 'none') AS bonustext
FROM employees;
Exercise
You write COALESCE(get_exchange_rate(order_id), 1) where get_exchange_rate queries a large table for every call. Most rows already have a rate stored in stored_rate. How should the query be written to avoid unnecessary calls, and what behavior makes this work?
Show answer
Put the cheap value first: COALESCE(stored_rate, get_exchange_rate(order_id), 1). COALESCE evaluates arguments left to right and stops at the first non-NULL value, so get_exchange_rate runs only for rows where stored_rate is NULL. NVL would evaluate both of its arguments for every row.