#Function
COALESCE()
The COALESCE()
function in MySQL is used to return the first non-NULL value from a list of expressions. If all expressions evaluate to NULL
, then COALESCE()
will return NULL
. It's often used to handle NULL
values in queries, replacing them with a default value or another column's value.
COALESCE(expr1,expr2,expr3)
SELECT name, COALESCE(email, 'No Email Provided') AS email
FROM users;
If the email
column contains NULL
for any user, 'No Email Provided'
will be returned instead of NULL
.
SELECT id, COALESCE(phone_home, phone_work, phone_mobile, 'No Phone Available') AS phone
FROM employees;
If phone_home
is NULL
, it will check phone_work
, then phone_mobile
, and if all of them are NULL
, it will return 'No Phone Available'
.
IFNULL() : - IFNULL(expression, default_value)