Sub topic 5
Replacing NULL with NVL
This chapter assumes you can write basic SELECT statements with WHERE and column aliases, and that you know the Oracle types NUMBER, VARCHAR2, and DATE. It also assumes you have seen that NULL propagates through arithmetic and that = never matches it. The examples use the Oracle sample HR schema, mainly the employees table, whose commission_pct column is NULL for most employees.
By the end you will be able to:
- use
NVLto substitute a default forNULL - predict the data type of the result
- avoid the common errors with it
What NVL does
NVL takes two arguments and returns the second one when the first is NULL. Otherwise it returns the first.
NVL(expr1, expr2)- If
expr1is notNULL, the result isexpr1. - If
expr1isNULL, the result isexpr2.
NVL does not change the stored data. It changes only what the query returns. The function is specific to Oracle. Other databases have similar functions with different names, such as IFNULL in MySQL and ISNULL in SQL Server.
Fixing a NULL in arithmetic
The most common use of NVL is repairing arithmetic. Any arithmetic with a NULL operand yields NULL. A pay calculation that includes commission_pct therefore loses every row where the commission is missing.
SELECT employee_id,
salary,
commission_pct,
salary + salary * commission_pct AS total_with_null,
salary + salary * NVL(commission_pct, 0) AS total_pay
FROM employees;For an employee with no commission, total_with_null is NULL. In total_pay, NVL(commission_pct, 0) becomes 0, so the expression reduces to salary + salary * 0, which is just the salary. For an employee with a commission of 0.2, NVL returns 0.2 and both columns agree.
Choose the replacement value so that it is neutral for the operation. These are the usual choices:
| Operation | Neutral replacement | Reason |
|---|---|---|
| Addition or subtraction | `0` | Adding zero changes nothing. |
| Multiplication or division by it | `1` | Multiplying by one changes nothing. |
| String concatenation | `''` is not usable, use `' '` or a label | Oracle treats `''` as `NULL`, so it cannot be the replacement. |
The concatenation row is easy to get wrong. The next section explains why.
NVL and the empty string
Oracle treats a zero-length string as NULL. That means NVL sees a literal '' as a missing value.
SELECT NVL('', 'was null') AS result FROM dual;The result is was null. This has two practical consequences.
- A column that appears to hold an empty string actually holds
NULL.NVLwill replace it. NVL(col, '')can never replace anything with an empty value. The replacement''is itselfNULL, so the result staysNULL.
If you want a visible placeholder for a missing text value, use a real character such as '-', 'n/a', or a single space.
SELECT employee_id,
first_name || ' ' || NVL(last_name, '(no last name)') AS full_name
FROM employees;Concatenation with || is the one place where Oracle does not propagate NULL. 'abc' || NULL returns abc. For that reason NVL matters less for concatenation than for arithmetic. You mostly use it there to show a readable label instead of a blank.
Data type rules
NVL returns one value, so the two arguments must be able to share a type. Oracle applies these rules.
- If
expr1is character data, Oracle convertsexpr2to the type ofexpr1and returns aVARCHAR2. - If
expr1is numeric, Oracle compares the two arguments' numeric precedence. It converts the lower one to the higher one and returns that type. - If
expr1is a date or timestamp,expr2must convert to a date type.
Oracle performs these conversions implicitly. They fail when the replacement cannot be converted.
-- Raises ORA-01722 because 'none' cannot be converted to a number
SELECT NVL(commission_pct, 'none') FROM employees;
-- Works: convert the column to text first
SELECT NVL(TO_CHAR(commission_pct), 'none') AS commission FROM employees;In the first query, commission_pct is a NUMBER, so Oracle tries to turn 'none' into a number and raises ORA-01722: invalid number. The fix is to make the types agree on purpose. Converting the column with TO_CHAR makes both arguments character data.
Implicit conversion can also work against you in the other direction. The query below runs without an error, but it relies on Oracle reading the string as a number.
SELECT NVL(commission_pct, '0') FROM employees;Here '0' is silently converted to the number 0. The result is correct, but the code is fragile. If someone changes the replacement to '0.0 ' or to text from a different source, the failure moves to run time and may only appear on certain rows. Write 0 as a number and keep the types explicit.
The same rule applies to dates. Replacing a missing date with a string needs TO_CHAR on the date, and a string date literal depends on the session's NLS_DATE_FORMAT. Prefer a date literal or TO_DATE with an explicit format.
SELECT employee_id,
NVL(hire_date, DATE '1900-01-01') AS hire_date_or_default
FROM employees;Both arguments are expressions
Either argument can be any expression, not only a column and a literal. You can nest function calls, use scalar subqueries, or refer to other columns.
SELECT employee_id,
NVL(commission_pct, salary / 100000) AS rate
FROM employees;A second column as the replacement is a common pattern. For example, NVL(preferred_name, first_name) shows a preferred name when there is one and falls back to the legal first name otherwise.
Do not rely on the second argument being skipped when the first is not NULL. Oracle documents short-circuit evaluation for COALESCE, but you should assume NVL may evaluate both arguments. A replacement that is expensive, such as a scalar subquery or a user-defined function, may then run for every row even when the first argument is not NULL. A later chapter compares evaluation behavior in detail. Here, keep the second argument cheap.
NVL on aggregates and averages
NVL changes the question an aggregate answers. AVG ignores NULL values, so it averages only the rows that have a value. Replacing NULL with 0 first makes every row count.
SELECT AVG(commission_pct) AS avg_among_earners,
AVG(NVL(commission_pct, 0)) AS avg_across_everyone
FROM employees;In the sample data, only some employees have a commission. The first column is the average among them. The second column adds a zero for everyone else, so the divisor is the total number of employees and the result is much lower. Neither answer is wrong. They answer different questions, and you need to decide which one the report wants.
COUNT(column) also skips NULL, whereas COUNT(NVL(column, 0)) counts every row. SUM ignores NULL anyway, so NVL inside SUM changes nothing except when every value is NULL. In that case SUM returns NULL, and NVL(SUM(x), 0) returns 0. Put NVL outside the aggregate for that purpose.
SELECT NVL(SUM(commission_pct), 0) AS total_commission_pct
FROM employees
WHERE department_id = 999;No rows match, so SUM returns NULL. The outer NVL turns it into 0.
Using NVL in a WHERE clause
You can use NVL in a filter to treat missing values as a known value.
SELECT employee_id, commission_pct
FROM employees
WHERE NVL(commission_pct, 0) = 0;This returns employees whose commission is 0 or missing. It works, but it has a cost. Wrapping a column in a function usually stops Oracle from using an ordinary index on that column. If the query matters for performance, either write the condition explicitly or create a function-based index on the same expression.
SELECT employee_id, commission_pct
FROM employees
WHERE commission_pct = 0
OR commission_pct IS NULL;The explicit form is longer, but it uses the plain column and keeps NULL handling visible to the reader.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `ORA-01722: invalid number` | The replacement text cannot convert to the numeric first argument. | Convert the column with `TO_CHAR`, or use a numeric replacement. |
| Result is still `NULL` | The replacement is `''`, or the replacement is itself `NULL`. | Use a real value such as `0`, `' '`, or `'n/a'`. |
| Averages look too low | `NVL(x, 0)` added zeros to the rows being averaged. | Decide whether missing rows should count, and remove `NVL` if they should not. |
| Slow filter | `NVL(col, ...)` in `WHERE` hides the column from its index. | Use `IS NULL` explicitly or add a function-based index. |
| Wrong type in a view or `UNION` | The result takes the type of `expr1`. | Convert explicitly with `TO_CHAR`, `TO_NUMBER`, or `TO_DATE`. |
Exercise
A query returns NVL(commission_pct, 'none') and fails with ORA-01722. Explain why it fails and rewrite it so that it returns the text none for employees with no commission.
Show answer
commission_pct is a NUMBER, so Oracle converts the replacement 'none' to a number. That conversion is impossible, which raises ORA-01722. Convert the first argument to text so both arguments are character data: SELECT NVL(TO_CHAR(commission_pct), 'none') AS commission FROM employees;
Exercise
What does SELECT NVL(NVL('', ''), 'x') FROM dual; return, and why? Then say what AVG(NVL(commission_pct, 0)) computes that AVG(commission_pct) does not.
Show answer
It returns x. Oracle treats each '' as NULL, so the inner NVL('', '') returns NULL, and the outer NVL then substitutes 'x'. AVG(commission_pct) skips NULL rows and averages only employees who have a commission. AVG(NVL(commission_pct, 0)) counts every employee, with zero for those who have no commission, so it averages across everyone.