HomeMYSQLWhat is COALESCE() function?

What is COALESCE() function?

The COALESCE() function in SQL (including MySQL) is used to return the first non-NULL value from a list of expressions. It’s very handy when you want to handle NULL values in queries.

Syntax:

COALESCE(expression1, expression2, ..., expressionN)
  • It evaluates the expressions from left to right.
  • Returns the first non-NULL value.
  • If all values are NULL, it returns NULL.

Examples:

  1. Basic Example:
SELECT COALESCE(NULL, NULL, 'Hello', 'World');

Result:

Hello

Explanation: It skips the NULLs and returns the first non-NULL value 'Hello'.


  1. With Table Data:
    Suppose you have a table employees:
idfirst_namemiddle_namelast_name
1JohnNULLDoe
2JaneAnnSmith
3BobNULLNULL

You want to get a full name, using the middle name if available, otherwise skip it:

SELECT first_name, COALESCE(middle_name, '') AS middle, last_name
FROM employees;

Result:

first_namemiddlelast_name
JohnDoe
JaneAnnSmith
BobNULL

  1. Replacing NULL with a Default Value:
SELECT COALESCE(last_name, 'No Last Name') AS last_name
FROM employees;

Result:

last_name
Doe
Smith
No Last Name

Key Points:

  • COALESCE() can take two or more arguments.
  • It’s ANSI SQL standard, so works in most databases.
  • Useful for handling NULLs without complicated CASE statements.

Share: 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *