Skip to content
/Chapter 9 · Query Debugging and Common Mistakes
Lesson 9.3·garden_shop
Lesson 9.3

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 classic 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 fix is to count the thing you actually mean.

Pattern
-- fan-out join inflates count(*):
count(*)                 -- counts joined rows (line items)

-- count the thing you actually mean:
count(distinct o.order_id)
Schema · Garden ShopTable · order_items5 columns · 48 rows
Table · order_items

One row per line item within an order.

5 columns · 48 rows
order_item_id intorder_id intproduct_id intquantity intunit_price decimal
Your task

The starter reports inflated order counts because of theorder_items join. Fix it so each customer'sorder_count is the true number of orders they placed. Keep the customers sorted by customer_id.

SQL Workbench
query.sqlgarden_shop · SQL engine loading
⌘↵ to run
·
Expected answer
  • Columns: customer_id, order_count.
  • Rows: 16 customers who have placed orders.
  • count(distinct o.order_id) gives the true order count even with the order_items join.