Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 57/ 160
03. Joins & Relational Querying

Combining Joins with Aggregations Safely

Aggregate at the right grain before or after joins to keep metrics correct.

IntermediateAggregate Then Join · Grain Safety3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

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

Revenue by product name, aggregated firstQuery example
1Input dataStart from the source rows or state that the statement sees.
order_items
3 rows
order_items sample rows
idorder_idproduct_idqtyprice
110142249.5
2101841150
310242149.5
products
3 rows
products sample rows
idnamepricecategorystock
42SQL Notebook49.5books18
84Mechanical Keyboard150hardware5
11Query Mug12.99gifts33
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  p.name,3  s.units,4  s.revenue5FROM6  (7    SELECT8      product_id,9      SUM(quantity) AS units,10      SUM(quantity * unit_price) AS revenue11    FROM12      order_items13    GROUP BY14      product_id15  ) s16  JOIN products p ON p.id = s.product_id17ORDER BY18  s.revenue DESC;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/18
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative product totals3 sample rows
Representative product totals
nameunitsrevenue
Mechanical Keyboard48143952
SQL Handbook112111888
USB-C Hub3766563

Note: Illustrative product-level sums ordered by revenue descending; actual units and amounts depend on the order_items data.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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.

An integrity checkQuery example
1Input dataStart from the source rows or state that the statement sees.
orders
3 rows
orders sample rows
idcustomer_idstatusamountcoupon_code
1011paid249NULL
1022paid120WELCOME10
1031shipped89.5NULL
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  (3    SELECT4      SUM(amount)5    FROM6      orders7    WHERE8      created_at >= '2026-11-01'9  ) AS source_total,10  (11    SELECT12      SUM(revenue)13    FROM14      customer_report15  ) AS report_total;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/15
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative integrity comparison1 sample row
Representative integrity comparison
source_totalreport_total
1825018250

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.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

The two numbers should match exactly.

Key takeaway: COALESCE to 0, average from sums and counts, compare totals with the source.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Design

State the grain

Decide what one output row is, and list each metric with the table it comes from.

Focus at this step

one row per customer: orders, revenue, open_tickets

What to watch at this step
Grain
written down
Tip: use ← → to move between steps

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)

Join everything, then GROUP BY
Best for: Only one one-to-many table in the query

Strengths: Short and readable.

Watch out: Two or more one-to-many joins multiply rows and inflate metrics.

Aggregate each side, then join
Best for: Reports combining several one-to-many tables

Strengths: Correct for every metric; usually faster.

Watch out: More CTEs to write.

COUNT(DISTINCT) after a fan-out
Best for: Quick counts in exploration

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?
Interview tip: Say the grain out loud before writing SQL, then build one CTE per child table. Interviewers recognise that habit as the mark of someone who has been burned by wrong metrics.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Combining Joins with Aggregations Safely with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Top-N Per Group Using LATERAL Joins
Next topic
Querying Star Schemas (Joining Fact Tables to Multiple Dimension Tables)