Aggregation After Joins and NULL Handling

Counting, summing, pre-aggregating, and handling NULLs correctly after one-to-many and outer joins.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all
## Aggregation after joins
Use COUNT(DISTINCT ...) when joins multiply rows
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;

# Protect aggregates from one-to-many duplication.

Pre-aggregate before joining
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;

# Summarize large fact tables first, then join the result.

Use COALESCE for outer-join aggregates
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;

# Replace `NULL` with a friendlier value in results.

## NULL behavior
Expect NULLs on the optional side of outer joins
LEFT JOIN → right-side columns may be NULL
RIGHT JOIN → left-side columns may be NULL
FULL OUTER JOIN → either side may be NULL

# Missing matches appear as NULL-valued columns.

Recommended next

No recommendations yet.