SQL COALESCE
COALESCE returns the first non-NULL value from its arguments. It is the standard way to show a fallback when data is missing.
Its partner NULLIF(a, b) returns NULL when a equals b. A common use is avoiding division by zero.
Syntax
COALESCE(value1, value2, ..., fallback)
Try it yourself
Run the example below on a real PostgreSQL database, then change it and run it again. Nothing to install, no sign-up.
Examples
1. Fallback text
SELECT first_name, COALESCE(email, 'no email') FROM customers;
Missing emails show 'no email'.
2. Safe division
SELECT name, price / NULLIF(stock, 0) AS price_per_unit_in_stock FROM products;
Out-of-stock products return NULL instead of an error.
Common mistakes
- Mixing types: COALESCE(number_column, 'none') fails because 'none' isn't a number.
Practice: test yourself
This challenge is from our interactive course. Write the query and press Check answer.
Return every customer's first_name and email, showing 'no email' when the email is missing.
FAQ
Is COALESCE the same as IFNULL or ISNULL?
Similar. IFNULL is MySQL and ISNULL is SQL Server, both with two arguments. COALESCE is standard SQL and works everywhere.
Learn SQL step by step
65 hands-on exercises, streaks, a leaderboard and a certificate.