Wrong SQL Results Without Errors
A join that fans out can silently inflate your counts and sums. No error, just a wrong answer.
The most dangerous queries are the ones that look fine. They run without complaint and hand back a confident-looking number that happens to be wrong. The usual culprit is a fan-out join.
When you join
orders
to
order_items, each order is repeated once per line item. Now
count(*)
counts line items, not orders, so the totals come out too high.
The first fix to reach for is the join itself. If the question doesn't need
anything from
order_items, drop it, and the rows stop multiplying. When you do need it, say for
units bought alongside the order count, keep the join and count the thing
you actually mean.
-- fan-out join inflates count(*):
count(*) -- counts joined rows (line items)
-- count the thing you actually mean:
count(distinct o.order_id) Schema · Garden Shop Tables · order_items, customers, orders 3 tables
One row per line item within an order.
One row per customer. Some customers have no phone on file.
One row per order. Unshipped orders have a null shipped_date.
The starter reports each customer's order_count
and units_bought (the total quantity across their line items),
but the order counts are inflated by the order_items join. Fix
order_count so it is the true number of orders they placed, and
keep units_bought as it is. Keep the customers sorted by
customer_id.
Run your query to inspect the result.
Expected answer
- Columns: customer_id, order_count, units_bought.
- Rows: 16 customers who have placed orders.
- Customer 1 placed 3 orders and bought 8 units; count(*) would have said 6 orders.
Related
Indentation, casing, and aliasing conventions.
One-to-many joins can inflate totals.
Paste an error message and find the fix, from GROUP BY to constraint failures.
Debug filters that match nothing.
Group or aggregate every selected column.
Right-table WHERE filters remove unmatched rows.