Sub topic 9
How the arguments are evaluated
Every function in this tutorial takes several arguments, and the arguments can be more than column names. They can be function calls, subqueries, or expressions that raise errors. This chapter covers which of those arguments Oracle actually runs. For NVL and COALESCE the difference has no effect on a column or a literal, but it matters when an argument is expensive, has side effects, or can fail.
This chapter assumes you can read basic PL/SQL, because the experiments use a small package. It also assumes you know NVL, NVL2, and COALESCE from the earlier chapters, and that you know what a deterministic function is.
The two evaluation models
Oracle can handle a multi-argument function in one of two ways:
- Eager evaluation: Oracle computes every argument, then applies the function's rule to the results.
- Short-circuit evaluation: Oracle computes arguments from left to right and stops as soon as the result is known.
The Oracle documentation states that COALESCE uses short-circuit evaluation. It evaluates each expression in turn and checks whether the value is NULL. It does not evaluate all the expressions first. In practice NVL does not give you that guarantee. The common behavior is that NVL evaluates both of its arguments, even when the first one is not NULL and the second one is therefore not needed.
| Function | Evaluation behavior | Stops early? |
|---|---|---|
| NVL(a, b) | Typically evaluates both `a` and `b` | No guarantee |
| NVL2(a, b, c) | Treat all three as possibly evaluated | No guarantee |
| COALESCE(a, b, c, ...) | Evaluates left to right, stops at the first non-NULL | Yes, documented |
| CASE WHEN ... | Evaluates conditions in order, stops at the first match | Yes, documented |
The words "typically" and "no guarantee" are deliberate. The optimizer can rewrite expressions, and its behavior can differ between versions. Oracle documents the short-circuit rule for COALESCE and CASE. It does not promise that NVL always evaluates its second argument. Design your queries around the documented behavior, and use the experiments below as a way to see what your own database does.
Observing evaluation with a counter
You can see evaluation directly by making the second argument a function that counts its own calls. Run this in a schema where you can create a package:
CREATE OR REPLACE PACKAGE call_counter AS
FUNCTION slow_default RETURN NUMBER;
FUNCTION get_calls RETURN NUMBER;
PROCEDURE reset;
END call_counter;
/
CREATE OR REPLACE PACKAGE BODY call_counter AS
g_calls NUMBER := 0;
FUNCTION slow_default RETURN NUMBER IS
BEGIN
g_calls := g_calls + 1;
RETURN 0;
END slow_default;
FUNCTION get_calls RETURN NUMBER IS
BEGIN
RETURN g_calls;
END get_calls;
PROCEDURE reset IS
BEGIN
g_calls := 0;
END reset;
END call_counter;
/slow_default stands in for any costly or side-effecting expression. It increments a package variable each time it runs, and get_calls reads that variable. The variable is read through a function because SQL cannot reference package variables directly.
Now test NVL with a first argument that is never NULL:
EXEC call_counter.reset;
SELECT NVL(1, call_counter.slow_default()) AS result
FROM dual
CONNECT BY LEVEL <= 5;
SELECT call_counter.get_calls() AS calls_after_nvl FROM dual;The query returns 1 five times. With the typical NVL behavior, calls_after_nvl is 5: the default was computed once per row even though no row needed it.
Repeat the test with COALESCE:
EXEC call_counter.reset;
SELECT COALESCE(1, call_counter.slow_default()) AS result
FROM dual
CONNECT BY LEVEL <= 5;
SELECT call_counter.get_calls() AS calls_after_coalesce FROM dual;Here calls_after_coalesce is 0. The first argument is not NULL, so the engine never reaches the function.
Why this matters
Cost
If the fallback is an expensive function or a correlated subquery, NVL can run it for every row, including rows where the first argument has a value. On a table with millions of rows where 99% of values are present, that is 99% wasted work. COALESCE avoids the work for those rows.
SELECT e.employee_id,
COALESCE(e.commission_pct,
(SELECT AVG(commission_pct)
FROM employees
WHERE department_id = e.department_id)) AS effective_commission
FROM employees e;The subquery runs only for rows where commission_pct is NULL. An equivalent NVL query may run it for every row.
Errors in unused branches
If the fallback can raise an error, eager evaluation can make the whole query fail even though the fallback would never have been used. This package adds a function that always fails:
CREATE OR REPLACE FUNCTION fail_default RETURN NUMBER IS
BEGIN
RAISE_APPLICATION_ERROR(-20001, 'fallback was evaluated');
END fail_default;
/With COALESCE, the query below succeeds because the failing function is never reached:
SELECT COALESCE(1, fail_default()) AS result FROM dual;The equivalent NVL query can raise ORA-20001 when the engine evaluates both arguments:
SELECT NVL(1, fail_default()) AS result FROM dual;The same pattern appears in real queries. A fallback such as TO_NUMBER(text_column) can raise ORA-01722 on rows where text_column is not numeric, even when the first argument is present and the fallback is irrelevant. The error appears only in some rows, so it looks random.
Side effects
Functions that write to a table, send a message, or advance a sequence run once per evaluation. Putting one in the second argument of NVL can trigger it far more often than you intend. In SQL it is better to avoid side-effecting functions altogether. If you cannot, COALESCE gives you a documented guarantee about when they run. Remember that a function with side effects called from a query also cannot perform DML unless it is an autonomous transaction, so this is a design smell.
NVL2 and the three-argument question
NVL2(a, b, c) returns b when a is not NULL and c when it is NULL. Only one of b and c can be the result, so a short-circuit implementation could skip the other. Oracle does not document NVL2 as short-circuiting. If either branch is costly or can fail, write the logic with CASE, where the behavior is documented:
SELECT employee_id,
CASE
WHEN commission_pct IS NOT NULL THEN salary * (1 + commission_pct)
ELSE salary
END AS total_pay
FROM employees;CASE evaluates only the branch that matches. It also lets you test conditions other than NULL, which NVL2 cannot do.
Short-circuiting inside COALESCE
COALESCE with many arguments is evaluated strictly in order, so argument position carries meaning. Put the cheapest and most likely non-NULL source first.
SELECT contact_id,
COALESCE(mobile_phone,
work_phone,
home_phone,
lookup_phone_from_directory(contact_id),
'no phone on file') AS best_phone
FROM contacts;Here lookup_phone_from_directory is a placeholder for a slow function, for example one that calls out to another system. It runs only for contacts who have no mobile, work, or home phone. If you moved it to the front, it would run for every contact. The order of the list is therefore both a business rule (which source wins) and a performance decision (which source is tried first).
Things that look like evaluation problems but are not
- Data type conversion is separate from evaluation order. The data type rules from the previous chapter apply whether or not an argument is ever reached. A type mismatch in a later COALESCE argument can still raise an error at parse time, even if that argument never runs.
- Constant expressions can fail early. An expression built only from literals, such as
1/0, can be folded by the optimizer before the query runs. A branch you expected to be skipped may then still raiseORA-01476. Test with column-based or function-based expressions, not literals, when you check evaluation order. - Deterministic functions can be cached. If a function is declared
DETERMINISTICor the optimizer caches scalar subquery results, a function may run fewer times than your row count suggests. Your counter will then show a smaller number for NVL than the typical pattern. That is a sign of caching, not short-circuiting.
Choosing based on evaluation
| Situation | Use |
|---|---|
| Fallback is a literal or a plain column | NVL or COALESCE, whichever you prefer |
| Fallback is an expensive function or subquery | COALESCE, or CASE |
| Fallback can raise an error | COALESCE, or CASE |
| Several fallbacks in priority order | COALESCE, cheapest source first |
| Two branches with different logic, one of which is costly | CASE |
For simple cases the choice is a matter of style, and the next chapters compare NVL and COALESCE on the other dimensions. For anything that is not a literal or a column, default to COALESCE.
Exercise
A query uses NVL(discount, compute_discount(order_id)), and compute_discount takes 20 ms per call. About 95% of rows already have a value in discount. Explain why the query is slow, and rewrite it so that compute_discount runs only when needed.
Show answer
NVL typically evaluates both arguments, so compute_discount runs for every row, including the 95% that already have a discount. Rewrite it with COALESCE, which stops at the first non-NULL argument: COALESCE(discount, compute_discount(order_id)). The function then runs only for the 5% of rows where discount is NULL. CASE also works: CASE WHEN discount IS NOT NULL THEN discount ELSE compute_discount(order_id) END.
Exercise
Using the call_counter package, you run SELECT COALESCE(NULL, call_counter.slow_default()) FROM dual CONNECT BY LEVEL <= 3; after calling call_counter.reset. What does call_counter.get_calls() return, and why?
Show answer
It returns 3. The first argument is NULL on every row, so COALESCE moves on to the second argument and evaluates it. With three rows, slow_default runs three times. Short-circuiting saves work only when an earlier argument is not NULL.
Exercise
Why might NVL(x, TO_NUMBER(text_col)) fail on some rows even when x is never NULL? Name a function that would avoid the problem and say what guarantee it relies on.
Show answer
NVL typically evaluates the second argument for every row, so TO_NUMBER(text_col) raises ORA-01722 on any row where text_col is not numeric, whether or not the result is used. COALESCE avoids this because Oracle documents it as short-circuiting: it never evaluates TO_NUMBER(text_col) when x is not NULL. CASE gives the same guarantee.