COALESCE for NULLs
Part of the Beyond the Basics section of Coddy's SQL journey — lesson 3 of 27.
COALESCE returns the first argument that is not NULL:
COALESCE(nickname, first_name, 'Anonymous')Reads left to right and stops at the first non-null. It's the cleanest way to supply a fallback value in a query, with no CASE needed.
Common uses:
- Show
0instead ofNULLfrom aLEFT JOIN:COALESCE(SUM(amount), 0) - Pick the first non-empty optional field:
COALESCE(mobile, home, work)
Challenge
EasyAvailable tables and columns:
<strong>users</strong>:<strong>id</strong>,<strong>display_name</strong>,<strong>email</strong><strong>orders</strong>:<strong>user_id</strong>,<strong>amount</strong>
Return one row per user with:
idlabel:display_nameif set, elseemail, else'unknown'total_spent: sum of the user's orderamounts; users with no orders should show0(notNULL)
Order by id. Hint: a LEFT JOIN from users to orders plus COALESCE(SUM(...), 0) handles the missing rows.
Cheat sheet
COALESCE returns the first non-NULL argument:
COALESCE(nickname, first_name, 'Anonymous')Common uses:
- Fallback display value:
COALESCE(mobile, home, work) - Replace
NULLfromLEFT JOINaggregates:COALESCE(SUM(amount), 0)
Try it yourself
SELECT u.id,
-- label via COALESCE
-- total_spent via COALESCE(SUM(...), 0)
FROM users u
LEFT JOIN orders o ON o.user_id = u.id
GROUP BY u.id
ORDER BY u.id
This lesson includes a short quiz. Start the lesson to answer it and track your progress.