Function Reference

COALESCE

Replaces NULL with the first value from the list that is not NULL.

MySQL 8.1
COALESCE(value[, ...])

Parameters

value
Values to check, separated by commas

Return value

The first non-NULL value; NULL if all arguments are NULL

Examples

First non-NULL value

MySQL 8.1
SELECT COALESCE(NULL, NULL, 1, 2);
COALESCE(NULL, NULL, 1, 2)
1

Source from one of two fields

MySQL 8.1
SELECT event_id,
	metadata->>'$.utm_source' AS utm_source,
	metadata->>'$.utm_src' AS utm_src,
	COALESCE(
		metadata->>'$.utm_source',
		metadata->>'$.utm_src',
		'unknown'
	) AS source
FROM events
LIMIT 6;
event_idutm_sourceutm_srcsource
1tiktok<NULL>tiktok
2<NULL>emailemail
3<NULL>tiktoktiktok
4email<NULL>email
5email<NULL>email
6tiktok<NULL>tiktok

Details

Unlike IFNULL, it takes any number of arguments and checks them from left to right: this way you can take the value from the first filled column and give a fallback value as the last argument.

See also

Where to learn