Overview
Tables can hold null and non-null values. Yet, often we prefer to overlook those null values and this is whereCOALESCE()
steps in. It helps when we want to ignore null values while processing the data, by returning the first argument that is not null, while the remaining arguments from the first non-null argument are not evaluated.
If all arguments are null, the COALESCE function will return null.
Syntax
The syntax for theCOALESCE()
function is as follows:
COALESCE()
requires a minimum of two inputs.- It can take an unlimited number of arguments.
- Evaluation occurs sequentially from left to right, stopping at the first non-null value.
Examples
Here are some examples to illustrate the application ofCOALESCE()
:
Case #1: Returning the First Non-Null Value
In this example, we have a set of values. By using theCOALESCE()
function, we’re going to get the first non-null value from this set.
9
, the first value without null among the provided options.
Case #2: Handling NULL Value as the Last Argument
Let’s include NULL as the final argument and check the query output.3
because it returns the first non-null value.
Case #3: Handling NULL Value as the First Argument
Consider NULL as the first argument in the following example.1
, as it is the first non-null value of the argument.
Case #4: Handling Multiple NULL Values
In the following query, NULL appears in the first, second, fourth, and last positions.COALESCE()
function ignores the first two NULLs and returns the first non-null value, 3
. It does not process the subsequent NULL values.
Case #5: Handling All NULL Values
Assume that the given values are entirely composed of nulls.COALESCE()
function returns an empty value (null).
Case #6: COALESCE()
with Table Data
Imagine we have the employee_absent
table, which comprises a mix of NULL and non-null values:
SELECT
statement to display all the records:
COALESCE()
function on the absent
column. It retrieves names and absences (with out of office
for NULL values) for each employee.
Case #7: Error Output in COALESCE()
When specifying arguments with different datatypes, they should be convertible.
COALESCE()
function will generate an error, as shown below.