Replace `NULL` with a friendlier value in results.
Section: Aggregation after joins
Use COALESCE for outer-join aggregates
sql
sql
SELECT c.customer_id,
COALESCE(SUM(o.total_amount), 0) AS total_spent
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
GROUP BY c.customer_id;Explanation
Outer joins can produce `NULL` totals for unmatched rows. `COALESCE` turns them into `0` or another default.
Learn the surrounding workflow
Compare similar commands or jump into common fixes when this command is part of a bigger troubleshooting path.
Related commands
Same sheet · prioritizing Aggregation after joins
Use COUNT(DISTINCT ...) when joins multiply rows
Protect aggregates from one-to-many duplication.
Pre-aggregate before joining
Summarize large fact tables first, then join the result.
Expect NULLs on the optional side of outer joins
Missing matches appear as NULL-valued columns.