COALESCE functions in SQL

The COALESCE function in SQL is used to return the first non-NULL expression among its arguments. It takes a list of expressions and returns the first one that is not NULL. If all expressions evaluate to NULL, the function returns NULL.

SQL Syntax

COALESCE(expression1, expression2, ..., expressionN)

Example: Let's create an employees table.

SQL

CREATE TABLE Employees (
    employee_id INT PRIMARY KEY,
    first_name VARCHAR(50),
    middle_name VARCHAR(50),
    last_name VARCHAR(50)
);  

Load the data into the Employees table.

SQL

INSERT INTO Employees VALUES
(1, ‘Ashish’, NULL, 'Goel'),
(2, 'Arjun', 'Singh', 'Reddy'),
(3, 'Mika’, NULL, NULL);  

By executing the below query, we can see the data from the table.

SQL

SELECT * FROM Employees;

Table: Employees

Employee_IDFirst_NameMiddle_NameLast_Name
1AshishNULLGoel
2ArjunSinghReddy
3MikaNULLNULL

We want to get a full name where:

Here’s the query using COALESCE:

SQL

SELECT employee_id, first_name,
COALESCE(middle_name, last_name) AS preferred_name
FROM employees;

The result of the above query is shown below:

Employee_IDFirst_NamePreferred_Name
1AshishGoel
2ArjunSingh
3MikaNULL