What does COALESCE do?
SQLLevel: FoundationFundamentals (Easy)
What does COALESCE do?
Hints
- Define one output row and the source-table keys.
- Check duplicates, NULLs and the order of filtering and aggregation.
Answer
COALESCE returns the first non-NULL value in a list of arguments.
-- Returns discount if not null, otherwise 0
SELECT product_name, COALESCE(discount, 0) AS discount
FROM products;
-- Chain of fallbacks
SELECT COALESCE(preferred_name, first_name, 'Unknown') AS display_name
FROM users;
It short-circuits — once it finds a non-NULL value, it stops evaluating the rest.
Source and licence: SQL Interview Questions — Arda Kocadoru · MIT