← SQL and databases

NULL in calculations: COALESCE

Replace missing values with something readable.

Start this lesson

Any calculation with NULL gives NULL: 5 + NULL is NULL, and 'Hi ' || NULL is NULL. If you do not know one part, you do not know the result. COALESCE(a, b) returns a if it is not NULL, otherwise b. It is the usual way to show a friendly value, such as 'no email', in place of a gap.

SELECT name, COALESCE(email, 'no email') AS contact
FROM members;

Members with an email show it; the others show the words no email.

COALESCE can take more than two values and returns the first one that is not NULL: COALESCE(phone, email, 'none').

IFNULL(a, b) does the same as COALESCE with two values in SQLite.