SQL course · Join and aggregation method
How to Solve SQL Joins and Aggregations Correctly
Fix double-counted totals after joining orders to items, and learn a reliable grain-first method for SQL aggregation.
Original PostgreSQL examples · Learn the method, test the output, explain the result.
Core idea
One order can become several joined rows.
100 + 80 = 180
Bad join sum = 280
The direct answer
Fix the grain before fixing the SUM.
When a SQL total is too large after a join, inspect what one joined row represents. If one order has two line items, joining orders to items produces two rows carrying that order’s header amount. Summing the header amount after the join counts it twice. DISTINCT often hides the symptom without preserving the meaning of the question.
This lesson shows the input tables, a wrong query and its output, two correct solutions for different requested metrics, and a transfer task. It assumes you can read a basic JOIN; if not, begin with the SELECT and joins lesson. The SQL course options follow this introduction.
Course access
Choose your next step in SQL.
Review the current course options and access details here.
Heycademy Courses · Coming Soon
Master SQL with Heycademy
We’re preparing an interactive learning experience with practical exercises, skill assessments and personalized learning to help you build confidence and master new skills.
We’re putting the finishing touches on this course. Please check back for updates.
First principle
Name the entity each row represents.
An order header is one row per order. An order item is one row per item. A customer total is one row per customer. A join between orders and order items changes the grain from order to item when an order has several items. You must know whether you are summing a header amount once per order or an item amount once per item.
Write the target in plain English before writing SQL: “one row per customer, sum of each paid order’s header total.” That sentence tells you to aggregate order headers before a fan-out join or omit the item join entirely. If the task instead asks for product revenue, item rows are the correct grain.
Original dataset
Two orders, three items.
| order id | customer | order total |
|---|---|---|
| 10 | Ada | 100 |
| 11 | Ada | 80 |
| item id | order id | item amount |
|---|---|---|
| 1 | 10 | 60 |
| 2 | 10 | 40 |
| 3 | 11 | 80 |
CREATE TEMP TABLE orders (id integer PRIMARY KEY, customer text, total integer);
CREATE TEMP TABLE order_items (id integer PRIMARY KEY, order_id integer, amount integer);
INSERT INTO orders VALUES (10,'Ada',100),(11,'Ada',80);
INSERT INTO order_items VALUES (1,10,60),(2,10,40),(3,11,80);Order 10 contains two items that sum to 100. Order 11 contains one item worth 80. The expected customer revenue is 180 whether you calculate from the two order headers or the three item amounts. The row counts differ: two order rows become three joined item rows.
See the failure
The header value is copied onto each item row.
SELECT o.customer, SUM(o.total) AS revenue
FROM orders o JOIN order_items i ON i.order_id=o.id
GROUP BY o.customer;| customer | wrong revenue |
|---|---|
| Ada | 280 |
| joined order id | item id | header total carried forward |
|---|---|---|
| 10 | 1 | 100 |
| 10 | 2 | 100 |
| 11 | 3 | 80 |
The bad query computes 100 + 100 + 80. The SQL engine is doing exactly what the query requests. The error is the measure at the wrong grain. SUM(DISTINCT o.total) would happen to return 180 here, but if the two legitimate orders both had a total of 100, it would count only one of them. Distinct values are not distinct orders.
Keep building this skill
Apply the method on fresh SQL problems.
The course options are above. Return to the synced pricing block whenever you are ready.
Two valid repairs
Choose the table that owns the measure.
SELECT customer, SUM(total) AS revenue
FROM orders
GROUP BY customer;| customer | revenue |
|---|---|
| Ada | 180 |
When no item property is needed, omit the join. This is the simplest and easiest solution to verify.
SELECT o.customer, SUM(i.amount) AS revenue
FROM orders o JOIN order_items i ON i.order_id=o.id
GROUP BY o.customer;| customer | revenue |
|---|---|
| Ada | 180 |
This answer is appropriate only if item amounts represent the desired revenue and the item data is complete. Header totals and item sums can legitimately differ when shipping, tax, discounts or data quality rules are involved.
A five-step method
Debug the first point of row expansion.
- Define the output grain and the measure’s source table.
- Check whether each join is one-to-one, one-to-many or many-to-many.
- Count rows before and after each join on a tiny dataset.
- Aggregate at the measure’s own grain, then combine results if necessary.
- Add a counterexample with two orders of equal total to defeat a false
SUM(DISTINCT ...)repair.
PostgreSQL’s table-expression documentation describes joins and grouping. The method also applies to customers joined to addresses, projects joined to tasks, and invoices joined to payments.
Try a fresh case
What happens when both headers equal 100?
Change order 11’s header total to 100 and its single item amount to 100. The correct header total for Ada is now 200. Predict the bad query and SUM(DISTINCT o.total) before running them.
Show the checked answer
The bad joined-header sum is 100 + 100 + 100 = 300 because order 10 still appears twice. SUM(DISTINCT o.total) is 100 because it keeps one distinct numeric value, even though there are two separate orders. SUM(total) directly from orders gives the correct 200. The item sum also gives 200 with the revised item data.
Review any answer by comparing the expected two order identities with the rows entering the aggregate. The mistakes guide explains why DISTINCT is an unreliable patch for a grain problem.
When the item join is required
Pre-aggregate by the entity you intend to count.
Sometimes you need an item-derived measure and an order-derived measure in the same report. Calculate each at its own grain, then join the summaries. The example below reports Ada’s header revenue and item revenue separately. It also makes a discrepancy visible if the two measures differ because of shipping, tax or incomplete items.
WITH order_summary AS (
SELECT customer, SUM(total) AS header_revenue
FROM orders GROUP BY customer
), item_summary AS (
SELECT o.customer, SUM(i.amount) AS item_revenue
FROM orders o JOIN order_items i ON i.order_id=o.id
GROUP BY o.customer
)
SELECT o.customer,o.header_revenue,i.item_revenue
FROM order_summary o JOIN item_summary i ON i.customer=o.customer;| customer | header revenue | item revenue |
|---|---|---|
| Ada | 180 | 180 |
This is not a general instruction to join every report to an item summary. It is a way to protect two distinct measures when the task genuinely requires both. In a production schema, use a stable customer id rather than a display name as the join key, and decide whether customers without items should appear. The sample is small enough to verify by hand: order totals 100 + 80 and item amounts 60 + 40 + 80.
FAQ
Questions about this skill.
Why is SUM(DISTINCT total) unsafe?
It deduplicates numeric values, not order identities. Separate legitimate orders can share the same amount.
Should I always aggregate before joining?
Aggregate at the grain of the requested measure. Sometimes item-level aggregation after a join is exactly correct.
Can a LEFT JOIN also inflate totals?
Yes. Preserving unmatched left rows does not stop matched left rows from multiplying when several right rows exist.
Continue with the SQL course
Make this skill reliable on new data.
Return to the course options and choose the next learning step.