Aggregation After Joins and NULL Handling
Counting, summing, pre-aggregating, and handling NULLs correctly after one-to-many and outer joins.
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all
## Aggregation after joins
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.
## NULL behavior
More in SQL Joins
SQL Join Patterns and Pitfalls
Common SQL join mistakes, reusable templates, and correctness rules for production queries.
Join Performance, EXPLAIN, and Optimization
SQL join tuning with indexes, plan inspection, row reduction, and troubleshooting guidance.
Semi-Joins and Anti-Joins
High-value EXISTS, IN, NOT EXISTS, and LEFT JOIN IS NULL patterns for membership and missing-row queries.
Many-to-Many Joins and Bridge Tables
Many-to-many SQL join patterns with bridge tables, aggregation, filtering, and index guidance.
Self Joins and Hierarchies
SQL self join examples for managers, duplicates, comparisons, and basic hierarchy modeling.
INNER, LEFT, RIGHT, and FULL OUTER JOIN Patterns
Practical SQL patterns for inner, outer, and reconciliation-style joins, including full outer join emulation.