Aggregation After Joins and NULL Handling/Use COUNT(DISTINCT ...) when joins multiply rows

Protect aggregates from one-to-many duplication.

Section: Aggregation after joins

Use COUNT(DISTINCT ...) when joins multiply rows

sql
sql
SELECT c.customer_id,
       COUNT(DISTINCT o.order_id) AS order_count
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
GROUP BY c.customer_id;
Explanation

A one-to-many join can inflate counts unless you count distinct entity keys.

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
Pre-aggregate before joining
Summarize large fact tables first, then join the result.
OpenIn sheetsqlsame section
Use COALESCE for outer-join aggregates
Replace `NULL` with a friendlier value in results.
OpenIn sheetsqlsame section
Expect NULLs on the optional side of outer joins
Missing matches appear as NULL-valued columns.