Sub topic 8
Matching Data Types of Replacement Values
This chapter assumes you can write basic SELECT statements and use DUAL. It also assumes you know the main Oracle data types (NUMBER, VARCHAR2, DATE) and have met NVL, NVL2, and COALESCE in the earlier chapters. Here you will learn why a replacement value must fit the type of the expression it replaces, and what Oracle does when it does not.
Why the replacement value has a type
Every SQL expression has exactly one data type. The result of NVL(commission_pct, 0) is one column of values. It cannot be a number in some rows and text in others. When you supply a replacement, Oracle must fit both the original expression and the replacement into one result type.
If the two are already the same type, nothing special happens. If they differ, Oracle tries an implicit conversion, which is a conversion you did not write. If no conversion is possible, the query fails. Sometimes the implicit conversion succeeds but changes the result type in a way you did not intend.
How NVL resolves the types
For NVL(expr1, expr2), Oracle applies these rules:
| Type of `expr1` | What Oracle does | Result type |
|---|---|---|
| Character (`VARCHAR2`, `CHAR`) | Converts `expr2` to the type of `expr1` | `VARCHAR2` |
| Numeric | Converts the argument with the lower numeric precedence to the higher one | The higher-precedence numeric type |
| `DATE` or other | Converts `expr2` to the type of `expr1` if it can | Type of `expr1` |
If the conversion is impossible, you get an error. The conversion usually fails at run time for the rows that need it, not when the statement is parsed. A query can therefore appear to work on a small test set and fail later.
The classic failure: text into a number column
commission_pct is a NUMBER column. Replacing its NULLs with the word 'none' forces Oracle to convert 'none' to a number, which is impossible.
-- 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;The fix moves the conversion to the side you control. TO_CHAR(commission_pct) produces a VARCHAR2, so NVL now has a character first argument and a character replacement. The result is text. That is the trade-off: you get a readable label, but you can no longer do arithmetic on the column or sort it numerically.
Implicit conversion that works, and why to avoid it
Oracle accepts some mixed arguments because the text can be converted. This statement runs:
SELECT employee_id, NVL(commission_pct, '0') AS commission_pct
FROM employees;The string '0' converts to a number, so the result is numeric. Avoid this pattern for two reasons.
- It depends on the value.
'0'converts, but'0.5'may not. The conversion uses the session'sNLS_NUMERIC_CHARACTERSsetting. In a session that uses a comma as the decimal separator,'0.5'can raise ORA-01722. - It hides intent. A reader cannot tell whether you meant a number or text.
Write the replacement as a literal of the right type: NVL(commission_pct, 0).
The reverse case is quieter and more dangerous. When the first argument is character data, Oracle converts the replacement to character data, even if you meant a number:
-- phone_number is VARCHAR2; the 0 becomes the text '0'
SELECT employee_id, NVL(phone_number, 0) AS phone
FROM employees;This runs without error, but the result is text. If you later sort or compare this column as if it were a number, '9' sorts after '10'. Use '0' or a meaningful label like 'n/a' so the intent is visible.
Dates
A DATE column needs a DATE replacement. A string such as 'unknown' cannot become a date, and Oracle raises a date conversion error such as ORA-01858.
-- Keep the result a DATE: use a date value
SELECT employee_id,
NVL(hire_date, DATE '1900-01-01') AS hire_date_or_default
FROM employees;
-- Need a label? Convert the date to text explicitly, with a format
SELECT employee_id,
NVL(TO_CHAR(hire_date, 'YYYY-MM-DD'), 'unknown') AS hire_date_text
FROM employees;Use a DATE '...' literal or TO_DATE with an explicit format mask. A bare string like '01-JAN-1900' is converted using the session's NLS_DATE_FORMAT, so the same query behaves differently for different users.
Numeric precedence
When both arguments are numeric, Oracle returns the type with the higher precedence. From lowest to highest, the order is NUMBER, BINARY_FLOAT, BINARY_DOUBLE. So if the column is a NUMBER and the replacement is a BINARY_DOUBLE literal, the whole result becomes BINARY_DOUBLE. NUMBER values are converted to binary floating point, which can lose decimal precision.
SELECT NVL(CAST(NULL AS NUMBER), 1.5) AS number_result,
NVL(CAST(NULL AS NUMBER), 1.5d) AS double_result
FROM dual;The d suffix marks 1.5d as a BINARY_DOUBLE literal. For money and other exact decimal values, keep both arguments as NUMBER.
Checking the result type with DUMP
You do not need to guess the result type. The DUMP function reports the internal type code of an expression: Typ=1 is VARCHAR2, Typ=2 is NUMBER, and Typ=12 is DATE.
SELECT DUMP(NVL(CAST(NULL AS NUMBER), 0)) AS numeric_case,
DUMP(NVL(CAST(NULL AS VARCHAR2(10)), 0)) AS character_case,
DUMP(NVL(CAST(NULL AS DATE), SYSDATE)) AS date_case
FROM dual;The first column reports Typ=2, the second Typ=1 (the 0 was turned into text), and the third Typ=12. The CAST(NULL AS ...) form gives a NULL that carries a type, which is how you test a type rule without needing a table.
NVL2 and the types of its two outcomes
NVL2(expr1, expr2, expr3) tests expr1 but returns expr2 or expr3. The type of expr1 does not matter for the result. Instead, Oracle converts expr3 to the type of expr2. If expr2 is numeric, it uses numeric precedence. If expr2 is a literal NULL, expr3's type is used.
-- Fails: the first outcome is a number, 'Salary only' is not
SELECT employee_id,
NVL2(commission_pct, salary, 'Salary only') AS pay
FROM employees;
-- Works: both outcomes are text
SELECT employee_id,
NVL2(commission_pct, 'Salary + commission', 'Salary only') AS pay_type
FROM employees;The first query fails because 'Salary only' cannot become a number. Either make both outcomes the same type, or convert one side with TO_CHAR(salary).
COALESCE and the types of all its arguments
COALESCE(expr1, expr2, ..., exprN) has no single "replacement". Every argument is a candidate result, so all of them must share one type or be implicitly convertible to it. If all arguments are numeric, the highest numeric precedence wins. Otherwise, mixing in an incompatible type produces an error.
-- Every candidate is VARCHAR2, so the result is VARCHAR2
SELECT contact_id,
COALESCE(mobile_phone, work_phone, home_phone, 'no phone on file') AS best_phone
FROM contacts;Mistakes are easy to make with long lists, because only the last argument often looks like "the default". If that default is a different type from the columns, the whole call fails, even for rows where an earlier column was not NULL. Treat the whole argument list as a unit that must agree on type.
A decision path
The following diagram shows how to choose a fix when a replacement does not match.
Habits that prevent type errors
- Match the literal to the column. Use
0for numbers,DATE '...'for dates, and'text'for strings. - Convert explicitly with
TO_CHAR,TO_NUMBER, orTO_DATE, and give a format mask for dates and number formats that may include separators. - Avoid relying on
NLS_DATE_FORMATorNLS_NUMERIC_CHARACTERS. They change from session to session. - Decide whether you want a numeric result or a label. A label makes the column text, so you give up arithmetic and numeric sorting on it.
- Test with rows that actually contain NULLs, and check the result type with
DUMPwhen in doubt.
Exercise
A report runs SELECT NVL(manager_id, 'none') FROM employees; and fails with ORA-01722. Why does it fail, and how do you fix it if the report must show the word none?
Show answer
managerid is a NUMBER column, so Oracle tries to convert 'none' to a number and fails. Convert the column to text first: SELECT NVL(TOCHAR(manager_id), 'none') FROM employees; The result is now VARCHAR2.
Exercise
What data type does NVL(phonenumber, 0) return when phonenumber is a VARCHAR2 column, and why is that a risk if you later sort the column?
Show answer
It returns VARCHAR2. When the first argument is character data, Oracle converts the replacement 0 to the text '0'. Sorting then happens as text, so '9' sorts after '10'. Use a text replacement such as 'n/a', or convert the column to a number if numeric order is needed.
Exercise
Why does NVL2(commission_pct, salary, 'Salary only') fail, and give two ways to fix it.
Show answer
The second argument (salary) is numeric, so Oracle tries to convert the third argument, 'Salary only', to a number and fails. Fix 1: make both outcomes text, NVL2(commissionpct, TOCHAR(salary), 'Salary only'). Fix 2: make both outcomes numeric, for example NVL2(commission_pct, salary, 0).