SQL COALESCE Function Explained

The COALESCE function is used to return the first non-null value in the list of parameters. If all values in the parameter list are NULL, then NULL is returned.

Grammar:

COALESCE(value1, value2, ..., valuen)

Explanation of parameters:

  1. value1, value2, …, valuen: a list of parameters, which can be any expressions or column names.

Assume there is a table students with fields id, name, and age, where the age field can be NULL. By using the COALESCE function, you can return the age that is not NULL or a default value of 18.

SELECT id, name, COALESCE(age, 18) AS age
FROM students;
bannerAds