Sub topic 7
Returning the first non-NULL value with COALESCE
This chapter assumes you can write SELECT statements with WHERE and aliases, and that you know the NUMBER, VARCHAR2, and DATE types. It also assumes you know that NULL means "missing or unknown", and that you have met NVL and NVL2 in earlier chapters. You will learn how COALESCE works, where it beats NVL, and which type and syntax errors it can raise.
What COALESCE does
COALESCE takes a list of expressions and returns the first one that is not NULL. If every expression is NULL, it returns NULL.
COALESCE(expr1, expr2 [, expr3 ...])Oracle needs at least two arguments. A call with one argument fails with ORA-00938 (not enough arguments for function). There is no fixed upper limit that you will hit in practice.
NVL is the two-argument case of the same idea. These two expressions give the same result:
NVL(a, b)
COALESCE(a, b)The difference shows up when you have more than two candidates, or when data types and evaluation order matter.
A fallback chain
Suppose a contact can have three phone numbers, and any of them may be missing. You want the best one available, in order of preference. With NVL you would nest calls: NVL(mobile_phone, NVL(work_phone, NVL(home_phone, 'no phone on file'))). COALESCE states the same intent as a flat list.
First, create a small table to run this against:
CREATE TABLE contacts (
contact_id NUMBER PRIMARY KEY,
contact_name VARCHAR2(50),
mobile_phone VARCHAR2(20),
work_phone VARCHAR2(20),
home_phone VARCHAR2(20)
);
INSERT INTO contacts VALUES (1, 'Ana', '555-0101', '555-0102', NULL);
INSERT INTO contacts VALUES (2, 'Ben', NULL, '555-0202', '555-0203');
INSERT INTO contacts VALUES (3, 'Chloe', NULL, NULL, '555-0303');
INSERT INTO contacts VALUES (4, 'Dev', NULL, NULL, NULL);
COMMIT;Now the query:
SELECT contact_id,
COALESCE(mobile_phone, work_phone, home_phone, 'no phone on file') AS best_phone
FROM contacts;The result is:
| CONTACT_ID | BEST_PHONE |
|---|---|
| 1 | 555-0101 |
| 2 | 555-0202 |
| 3 | 555-0303 |
| 4 | no phone on file |
Ana has a mobile number, so it wins even though she also has a work number. Ben has no mobile number, so the work number is next. Dev has nothing, so the final literal is returned.
The last argument is usually a literal default. It acts as a guard: if you end the list with a value that can never be NULL, the whole expression can never be NULL.
How the arguments are evaluated
Oracle evaluates COALESCE from left to right and stops at the first non-NULL value. This is called short-circuit evaluation. The remaining arguments are not evaluated at all.
This matters when a later argument is expensive or can fail. A later argument might call a PL/SQL function, run a scalar subquery, or contain a division. If an earlier argument already supplied a value, that later work is skipped. NVL has no such guarantee, so don't rely on NVL to skip its second argument. A later chapter compares the two functions in detail.
Data type rules
All arguments must be of the same data type or convertible to a common one. Oracle works out the result type from the arguments:
- If all arguments are numeric, or can be implicitly converted to a number, Oracle picks the numeric type with the highest precedence, converts the rest to it, and returns that type.
- If all arguments are character types, the result is a character string.
- If the types cannot be reconciled, the statement fails at run time or parse time.
The usual mistake is putting a text fallback after a numeric column. The fix is the same as for NVL: convert the column first.
-- Fails: a number column with a text fallback
SELECT COALESCE(commission_pct, 'none') FROM employees;
-- Works: convert the number to text first
SELECT COALESCE(TO_CHAR(commission_pct), 'none') AS commission
FROM employees;The same applies to dates. To show "not set" in place of a NULL end_date, wrap the date in TO_CHAR and pick the format yourself, so the result does not depend on the session's NLS date format:
SELECT employee_id,
COALESCE(TO_CHAR(end_date, 'YYYY-MM-DD'), 'still employed') AS end_text
FROM job_history;The next table summarizes which combinations work.
| Argument mix | Result |
|---|---|
| NUMBER, NUMBER | NUMBER |
| VARCHAR2, VARCHAR2 | VARCHAR2 |
| DATE, DATE | DATE |
| NUMBER, VARCHAR2 literal such as `'none'` | Error, because `'none'` cannot become a number |
| NUMBER, VARCHAR2 containing only digits, such as `'0'` | Can succeed through implicit conversion, but avoid relying on it |
Implicit conversion is fragile. A string that holds digits today can hold text tomorrow, and the query will then fail. Use explicit TOCHAR, TONUMBER, or TO_DATE.
Mixing columns and expressions
Arguments can be any expressions: columns, literals, arithmetic, function calls, or scalar subqueries. A common use is to fall back to a different calculation:
SELECT employee_id,
COALESCE(commission_pct * salary, salary * 0.05, 0) AS bonus
FROM employees;Remember that NULL propagates through arithmetic. If commission_pct is NULL, commission_pct * salary is NULL, so COALESCE moves on to the next argument. Because salary * 0.05 is NULL only when salary is NULL, the final 0 catches that case.
COALESCE also works anywhere an expression is allowed, not only in the SELECT list.
-- In a filter: treat a missing end date as "far in the future"
SELECT contact_id
FROM contacts_history
WHERE COALESCE(valid_to, DATE '9999-12-31') > SYSDATE;
-- In ORDER BY: sort employees with no commission as if it were zero
SELECT employee_id, commission_pct
FROM employees
ORDER BY COALESCE(commission_pct, 0) DESC;In the filter example, valid_to > SYSDATE alone would silently drop every row where valid_to is NULL, because the comparison is unknown. COALESCE keeps those rows by turning the NULL into a value that always compares as true.
A function applied to a column in a WHERE clause can stop Oracle from using a normal index on that column. If that filter is hot, consider a function-based index on the exact COALESCE expression.
Empty strings
Oracle treats a zero-length string as NULL, so COALESCE skips it just as it skips any NULL:
SELECT COALESCE('', 'was empty') AS result FROM dual;This returns was empty. The consequence is that you cannot use COALESCE to tell "empty" from "missing" in Oracle. Both are NULL before the function sees them.
When every argument can be NULL
If you leave off the final default and all arguments are NULL, the result is NULL. That is sometimes what you want, for example when the caller has its own handling. When it is not, end the list with a literal. This catches people when a new column is added to the chain later: the old final default is no longer last, and the expression can again return NULL.
-- Can still return NULL when all three columns are NULL
SELECT COALESCE(mobile_phone, work_phone, home_phone) AS best_phone
FROM contacts;Common errors
| Symptom | Cause | Fix |
|---|---|---|
| ORA-00938: not enough arguments for function | Only one argument passed | Provide at least two arguments |
| ORA-00932 or ORA-01722 | Argument types cannot be reconciled, for example a number column with `'none'` | Convert with TO_CHAR, TO_NUMBER, or TO_DATE so all arguments share a type |
| Result still NULL | All arguments were NULL, or an empty string was passed as the default | End the list with a non-empty literal |
| Result shows a number where you expected text | Implicit conversion picked the numeric type | Cast explicitly |
| Odd date output | Implicit DATE to text conversion depends on NLS settings | Use TO_CHAR with a format mask |
COALESCE with other NULL tools
COALESCE combines well with the functions you already know. NULLIF, covered in a later chapter, does the opposite job: it turns a specific value into NULL. Together they let you normalize data. For example, COALESCE(NULLIF(TRIM(nickname), ''), first_name) uses the nickname unless it is blank, in which case it falls back to first_name. In Oracle, TRIM on a blank string already yields NULL, so the NULLIF is redundant for that case. It is still useful for placeholders like 'N/A':
SELECT contact_id,
COALESCE(NULLIF(work_phone, 'N/A'), mobile_phone, 'no phone on file') AS best_phone
FROM contacts;Here the placeholder 'N/A' becomes NULL, so COALESCE treats it as missing and moves on.
Key points
- COALESCE returns the first non-NULL argument, or NULL if there is none.
- It requires two or more arguments and handles any number beyond that.
- Arguments are evaluated left to right and evaluation stops at the first non-NULL value.
- All arguments must share a type or convert to one. Convert explicitly rather than relying on implicit conversion.
- End the list with a literal when the result must never be NULL.
Exercise
A table orders has columns ship_date (DATE), promised_date (DATE), and order_date (DATE, never NULL). Write a query that returns order_id and one date called best_date, using ship_date if present, otherwise promised_date, otherwise order_date. Why is no extra default needed at the end of the list?
Show answer
SELECT orderid, COALESCE(shipdate, promiseddate, orderdate) AS bestdate FROM orders; Because `orderdate` is never NULL, the expression can never return NULL, so the list already ends in a guaranteed value.
Exercise
The query SELECT COALESCE(salary, 'unknown') FROM employees fails. Explain why, and write a corrected version.
Show answer
salary is a NUMBER and 'unknown' is text that cannot be converted to a number, so the argument types are incompatible. Convert the column first: SELECT COALESCE(TOCHAR(salary), 'unknown') AS salarytext FROM employees;
Exercise
What does SELECT COALESCE('', '', 'x') FROM dual return in Oracle, and why?
Show answer
It returns x. Oracle treats each empty string as NULL, so COALESCE skips the first two arguments and returns the first non-NULL value.