COALESCE
- SQL course
- Beginner
- Lesson 61/115
- 4 min
Provide a default value for NULL with COALESCE.
COALESCE
COALESCE returns the first non-NULL value from a list. It is used to give a default instead of NULL.
SELECT COALESCE(phone, 'yok') AS tel FROM customers;This query writes 'yok' when phone is null.
COALESCE(phone, 'yok') AS tel is selected from customers.
COALESCE — details
You can give several fallbacks: COALESCE(a, b, c). If all are NULL the result is NULL. Ideal for filling empty cells in reports.
Practice COALESCE
Select phone with 'none' as fallback aliased as tel from customers.
Starter code
-- fallback value
SELECT
FROM customersSample solution
SELECT COALESCE(phone, 'yok') AS tel
FROM customersExpected output
tel 555-1234 yok
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 COALESCE: match the terms
| Term | Meaning |
|---|---|
COALESCE |
first filled |
NULL |
null |
IS NULL |
check |
0 |
zero |
2 Fallback value
SELECT ____(phone, 'yok') FROM customers;
SELECT COALESCE(phone, 'yok') FROM customers;
Explanation: COALESCE is the right answer.
3 What does COALESCE return?
- An empty value
- All values
- The first NULL value
- The first non-NULL value Correct answer
Explanation: COALESCE gives the first non-NULL value.