Function or operator · Filters and conditions

COALESCE

COALESCE returns its first argument that is not NULL. If every argument is NULL, it returns NULL.

Before continuing: This entry is part of the NULL guide. If you are new to the topic, start with IS NULL / IS NOT NULL.

COALESCE example

SQL
SELECT id, name,
       COALESCE(email, 'No email') AS email_visible
FROM customers
WHERE id IN (1, 4)
ORDER BY id;

What to look for: In a row where email is NULL, the column email_visible shows «No email». If the customer does have an email address, the original value is kept. The data stored in the table does not change.

Check the result with small data

One customer has an email address and the other does not.

Self-contained query · SQLite
WITH customers(name, email) AS (
  VALUES ('Amy','amy@test.local'),('Liam',NULL)
)
SELECT name, COALESCE(email,'No email') AS visible
FROM customers ORDER BY name;
Query result
namevisible
Amyamy@test.local
LiamNo email

COALESCE replaces the NULL only in the query output; it does not store «No email» in the table. Choose a label that cannot be mistaken for real data.

Check your understanding: What would COALESCE(NULL, NULL, 'Pending') return?

Show answer

'Pendiente'. COALESCE returns the first argument that is not NULL; if all of them were NULL, it would return NULL.

Common mix-ups with COALESCE

Making up a value that looks real

Problem query
SELECT COALESCE(return_date, CURRENT_DATE)
FROM loans;

An unknown return date is not the same as a book returned today. This expression can make an active loan look closed. For display, use an unambiguous label such as “Pending”, or derive a status with CASE.

Choosing a fallback value without hiding the original data

A substitution should meet a specific need. To display a phone number you might use “No phone”; to add up revenue, a zero may make sense only if a missing value really means there was no amount. An unknown value, a sale of zero pounds and a row that does not exist are three different states. Turning them all into zero simplifies one calculation but can erase information you need to read the report.

Where you put COALESCE also changes the calculation. The average of 10 and an unknown value is 10 when the aggregate ignores the null. Replacing that null with zero first gives an average of 5. Neither version tells you on its own which policy is right: decide whether the second record should count in the denominator and document the rule.

In an outer join, keep both the key from the matched side and the original value while reviewing. Only then apply the display label. Also, COALESCE does not treat an empty string as null: an empty string can win over a fallback phone number. If empty strings mean “missing” in your data, normalise them explicitly and check that you are not discarding valid values.

Technical questions: PostgreSQL: conditional expressions (opens in a new tab).