The short answer
COALESCE() takes a list of values and returns the first one that isn’t NULL. If every value in the list is NULL, it returns NULL.
SELECT COALESCE(NULL, NULL, 'backup', 'last resort');
-- Returns 'backup'
How the list is read
The values are checked from left to right. Put the value you prefer first, and the fallbacks after it. The list can have as many values as you need.
The values should be the same type or compatible types. Mixing types can cause conversion errors or results you don’t expect, so check the types in your database.
Filling a blank column
COALESCE is often used to fill a blank column from a backup value:
UPDATE customers
SET phone = COALESCE(phone, home_phone, 'No phone')
WHERE phone IS NULL;
For each row where phone is empty, the update uses home_phone if that has a value. If it is also empty, the update stores ‘No phone’. Placeholder text like that can be mistaken for real data later, so decide whether you want it before you run the update.
Other names for the same idea
Other databases have their own names for a two-value version:
- MySQL:
IFNULL(a, b) - SQL Server:
ISNULL(a, b) - Oracle:
NVL(a, b)
COALESCE accepts any number of values and is part of standard SQL, and it works in these databases too.
Empty strings are not NULL
COALESCE only skips NULL. An empty string ('') is a value, so COALESCE returns it. If blanks are stored as empty strings, convert them with NULLIF(column, ''), which returns NULL when the column is empty. Spaces need trimming first, and what does trim() do in sql explains that.
Related questions
If you want to join two columns’ text together rather than pick one, that is a different job, covered in how to combine 2 column into 1 column. For showing zeros in place of NULL, see how to get 0 instead of null in sql.