Combining Joins with Aggregations Safely
Aggregate at the right grain before or after joins to keep metrics correct.
In plain words
Add things up for each table on its own first, then put the totals together.
Think of it like…
Combining two class reports: first get each teacher's total per student, then put the totals side by side. If you staple every homework sheet to every test paper first, each mark ends up counted several times.
Where you’ve seen it
A customer health report needs order count, revenue and open tickets per customer: WITH o AS (SELECT customer_id, COUNT(*) AS orders, SUM(amount) AS revenue FROM orders GROUP BY customer_id), t AS (SELECT customer_id, COUNT(*) AS open_tickets FROM tickets WHERE status = 'open' GROUP BY customer_id) SELECT c.id, c.name, COALESCE(o.orders, 0) AS orders, COALESCE(o.revenue, 0) AS revenue, COALESCE(t.open_tickets, 0) AS open_tickets FROM customers c LEFT JOIN o ON o.customer_id = c.id LEFT JOIN t ON t.customer_id = c.id;
Words you’ll hear
- Grain
- What one row of a table or result represents.
- Aggregate then join
- Bring each child table to the report's grain before joining.
- Pre-aggregated CTE
- A CTE with one row per key, safe to join one-to-one.
- Weighted average
- An average over the underlying rows, not an average of averages.
Visual diagram
Theory & example queries
Decide the grain, then aggregate to it
Write down what one output row means: "one row per customer" or "one row per product per day". Every table you join must then contribute at most one row per key at that grain. Lookup tables (customers, products) already do. One-to-many tables (orders, tickets, payments) need GROUP BY on the report's key first.
COUNT(DISTINCT o.id) can rescue counts after a fan-out, but it can't rescue SUMs: SUM(amount) still adds each duplicated order several times, and SUM(DISTINCT amount) wrongly collapses two different orders that happen to have the same amount. Pre-aggregating is the fix that works for every metric. It's often faster too, because the joins operate on thousands of summary rows instead of millions of detail rows.
| id | order_id | product_id | qty | price |
|---|---|---|---|---|
| 1 | 101 | 42 | 2 | 49.5 |
| 2 | 101 | 84 | 1 | 150 |
| 3 | 102 | 42 | 1 | 49.5 |
| id | name | price | category | stock |
|---|---|---|---|---|
| 42 | SQL Notebook | 49.5 | books | 18 |
| 84 | Mechanical Keyboard | 150 | hardware | 5 |
| 11 | Query Mug | 12.99 | gifts | 33 |
SELECT p.name, s.units, s.revenueFROM ( SELECT product_id, SUM(quantity) AS units, SUM(quantity * unit_price) AS revenue FROM order_items GROUP BY product_id ) s JOIN products p ON p.id = s.product_idORDER BY s.revenue DESC;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Representative product totals3 sample rows
| name | units | revenue |
|---|---|---|
| Mechanical Keyboard | 48 | 143952 |
| SQL Handbook | 112 | 111888 |
| USB-C Hub | 37 | 66563 |
Note: Illustrative product-level sums ordered by revenue descending; actual units and amounts depend on the order_items data.
Key takeaway: Every joined input should have at most one row per report key.
Zeros, averages and checks
With LEFT JOIN to pre-aggregated results, customers with no orders get NULL, so wrap metrics in COALESCE(…, 0). When you count children directly after a LEFT JOIN, use COUNT(o.id), not COUNT(*), or customers with no orders show a count of 1.
Averages need care. The average order value across all orders is SUM(amount) / COUNT(*) over orders, which is not the average of each customer's average. Compute averages from sums and counts at the level you mean. Finally, check metric integrity: the total of revenue in your report should equal SELECT SUM(amount) FROM orders under the same filters; if it's bigger, something fanned out.
| id | customer_id | status | amount | coupon_code |
|---|---|---|---|---|
| 101 | 1 | paid | 249 | NULL |
| 102 | 2 | paid | 120 | WELCOME10 |
| 103 | 1 | shipped | 89.5 | NULL |
SELECT ( SELECT SUM(amount) FROM orders WHERE created_at >= '2026-11-01' ) AS source_total, ( SELECT SUM(revenue) FROM customer_report ) AS report_total;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Representative integrity comparison1 sample row
| source_total | report_total |
|---|---|
| 18250 | 18250 |
Note: Assumes customer_report covers the same November 2026 rows and filters. Equality validates this illustrative reconciliation, not a guarantee for other grains or date filters.
The two numbers should match exactly.
Key takeaway: COALESCE to 0, average from sums and counts, compare totals with the source.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
State the grain
Decide what one output row is, and list each metric with the table it comes from.
one row per customer: orders, revenue, open_tickets
When to use it & trade-offs
What it is
When a report combines several tables, decide the grain first (one row per customer, per day, per product), then bring every table to that grain *before* joining. The safe habit is aggregate, then join: total each one-to-many table per customer in its own subquery or CTE, then join those one-row-per-customer results together. Joining raw tables first and aggregating at the end multiplies rows and inflates SUMs and COUNTs.
Why it matters: Metrics that are silently wrong are worse than queries that fail. A customer report with orders, revenue and support tickets is a classic case where joining everything first doubles numbers for anyone with more than one ticket. Interviewers often give exactly this task to see whether you think about grain before you write the join.
When to reach for it
- Customer, product or account summary reports
- Dashboards combining orders, payments and tickets
- Any query with two or more one-to-many joins
When to avoid or be careful
- Summing amounts after joining two child tables
- COUNT(*) after a LEFT JOIN when you mean child rows
- Averaging per-group averages
Join-then-aggregate vs aggregate-then-join vs COUNT(DISTINCT)
Strengths: Short and readable.
Watch out: Two or more one-to-many joins multiply rows and inflate metrics.
Strengths: Correct for every metric; usually faster.
Watch out: More CTEs to write.
Strengths: Fixes counts with little effort.
Watch out: Doesn't fix SUM or AVG; hides the real problem.
Interview signals & numbers to know
When this topic comes up
- “Orders, revenue and tickets per customer in one query”
- “The revenue total is higher than finance's number”
- Grain of a report
- Metrics after joins
- CTE per metric
Benchmarks & rules of thumb
- 1
- row per key in every joined input
- 0
- difference allowed between report and source totals
- COUNT(o.id)
- not COUNT(*) after a LEFT JOIN
Common mistakes & follow-ups
Common interview mistakes
- Joining orders and tickets to customers and summing amount, so a customer with 3 tickets has revenue tripled.
- Fixing inflated counts with COUNT(DISTINCT) and leaving the inflated SUM in the same query.
- Reporting AVG(customer_avg_order_value) as the overall average order value.
Likely interviewer follow-ups
- Write a query with order count, revenue and open tickets per customer.
- How would you prove a report's numbers are correct?
- Why doesn't COUNT(DISTINCT) fix an inflated SUM?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Combining Joins with Aggregations Safely with hands-on SQL practice and interview Q&A.