Aggregation After Joins and NULL Handling/Pre-aggregate before joining

Summarize large fact tables first, then join the result.

Section: Aggregation after joins

Pre-aggregate before joining

sql
sql
WITH order_totals AS (
  SELECT customer_id, SUM(total_amount) AS total_spent
  FROM orders
  GROUP BY customer_id
)
SELECT c.customer_id, c.name, ot.total_spent
FROM customers c
LEFT JOIN order_totals ot ON ot.customer_id = c.customer_id;
Explanation

This often improves both correctness and performance.

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.
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.