Fix the bug: a JOIN that doubles your revenue
The last two lessons had queries that returned obviously wrong answers - zero
rows, or too few rows. This bug is worse, because the output looks like a
real report. Right column names, right shape, numbers in a sane range. You'd
have to already know the right answer to catch it just by looking.
orders holds one row per order. shipments holds one row per shipment -
and some orders ship in more than one package, so they get more than one row
in shipments. Joining orders to shipments to find out who has a shipped
order is fine. Joining them and then SUMing the order amount is not: an
order with two shipment rows joins into two output rows, and SUM adds its
amount in twice. The order didn't get more expensive. It just has more rows
next to it.
Look at Ana. She has two orders, worth 100 and 50. Her first order shipped in
two packages. Add the shipment counts and you can already see the fan-out
coming before you touch a query.
Your task: return each customer's total revenue, counting only orders
that have shipped, without double-counting an order that shipped in more than
one package. The answer is Ana 150, Luka 200, Marta 80.
You'll practice:
Noticing a JOIN + SUM that inflates totals when the joined table has
more than one row per parent
Filtering "has at least one match" with EXISTS instead of joining and
summing over the duplicates
Show a hint
Show solution
Previous Next