The COALESCE function in Oracle is used to return the first non-NULL expression among its arguments. It is a very useful function for handling NULL values and ensuring that some meaningful data is returned even when some inputs might be NULL.
Syntax
- expr1, expr2, ..., exprn: These are the expressions to be evaluated.
COALESCEwill return the first non-NULL expression in this list. If all expressions evaluate to NULL, theCOALESCEfunction will return NULL.
Key Points
COALESCEcan take two or more arguments.- The expressions can be of any data type, but they must all be compatible.
- It stops evaluating expressions as soon as it finds the first non-NULL expression.
Examples
Basic Usage
Suppose you have a table employees with the columns first_name, middle_name, and last_name. You want to get the first non-NULL name from these columns for each employee.
COALESCE(first_name, middle_name, last_name) AS primary_name
FROM employees;
Handling NULL Values in Aggregation
If you have a sales table and you want to sum up the sales but treat NULL values as 0, you can use COALESCE:
FROM sales;
Providing Default Values
You can use COALESCE to provide a default value for a column that might contain NULL values.
COALESCE(phone_number, 'N/A') AS contact_number
FROM employees;
Using COALESCE in INSERT Statements
When inserting data into a table, you can use COALESCE to ensure that NULL values are replaced with a default value.
VALUES (1, 'John', 'Doe', COALESCE(NULL, 'No Phone'));
Comparison with NVL
COALESCE is similar to NVL, but more flexible:
NVL(expr1, expr2): Ifexpr1is NULL,NVLreturnsexpr2. Otherwise, it returnsexpr1.COALESCE(expr1, expr2, ..., exprn): Returns the first non-NULL expression in the list.
Example using NVL:
NVL(middle_name, 'N/A') AS middle_name
FROM employees;
COALESCE (which can handle more than two expressions):Conclusion
The COALESCE function is a powerful tool for handling NULL values in Oracle SQL. It can be used to provide default values, ensure non-NULL results in expressions, and simplify handling of multiple potential NULL values in a list of expressions. It is particularly useful in complex queries and data transformation processes where ensuring non-NULL values is critical.