Coalesce Function


The COALESCE function in SQL is used to return the first non-null expression from a list of expressions. It takes multiple arguments and returns the value of the first argument that is not null. If all arguments are null, then COALESCE returns null.

The syntax for the COALESCE function is as follows:

COALESCE(arg1, arg2, ..., argN)

Each argument can be a column name, a constant value, or another function.

Here’s an example to illustrate how the COALESCE function works:

SELECT COALESCE(column1, column2, 'N/A') AS result
FROM your_table;

In this example, if column1 is not null, its value will be returned. If column1 is null and column2 is not null, then column2 will be returned. If both column1 and column2 are null, then the string 'N/A' will be returned as the result.

The COALESCE function is commonly used in SQL queries to handle situations where you want to display a default value when a specific column has a null value or to perform conditional logic based on nullability.