Skip to main content
Back to Academy🚨 0. Analytics Foundations (Start Here)
5 min read
Try Hands-on Lab
VISUAL LESSON0. Analytics Foundations (Start Here)

SQL JOINs Visualized & Avoiding the Fan-Out Trap

A visual, row-by-row guide to INNER, LEFT, FULL OUTER JOINs and how joining parent and child tables at different grains causes silent revenue duplication (the Fan-Out Trap).

SQL JOIN types explainedINNER JOIN vs LEFT JOINSQL Fan-Out TrapMany-to-Many Join DuplicationCTE Pre-Aggregation SQLData Grain Mismatch

Explain Like I'm New: The Wedding Seating Chart

Imagine you have two clipboards at a wedding: - Clipboard A (`orders`): 1 line per Order (Order #101: Total Shipping Fee = $10). - Clipboard B (`order_items`): 3 lines for Order #101 (Shoes, Hat, Belt).

If you staple every item line directly onto the Order clipboard (JOIN), Order `#101` gets cloned 3 times, and the $10 Shipping Fee suddenly shows up on 3 rows ($10 + $10 + $10 = $30)! You accidentally tripled your shipping revenue.

That accidental cloning is called a SQL Fan-Out Trap (or cardinality explosion). Understanding joins means tracking "what 1 row represents" before and after every JOIN.

Key Beginner Takeaway: Always check how many matching rows exist on the right side of a join. If 1 left row matches 3 right rows, your left row will duplicate 3 times—inflating any SUM() or COUNT() on left-table metrics!

Visual Guide to Core SQL JOIN Types

JOIN TypeWhat Survives in Result?Missing Match BehaviorEveryday Use Case
`INNER JOIN`Only rows with a matching key in both tables.Drops unmatched rows from both sides.Show only orders placed by verified registered users.
`LEFT JOIN`All rows from Left table + matches from Right.Right columns become NULL if no match.Keep all customers—even those with 0 orders yet.
`FULL OUTER JOIN`All rows from both Left and Right tables.Unmatched cells on either side become NULL.Finance reconciliation (Stripe payouts vs. Bank ledger).
`CROSS JOIN`Every left row paired with every right row (N x M).No ON clause. Dangerous by accident, great for calendars!Generate 365 days x 50 stores grid before left-joining sales.
Semi-Join (`EXISTS`)Left rows that have >= 1 match in Right (no cloning!).Never duplicates Left rows even on 1-to-many matches.Find customers who bought *at least one* item cleanly.

Tracing the Fan-Out Trap Step-by-Step

Let's test this on real sample tables so you can watch the bug happen with your own eyes.

Table 1: `orders` (Grain: 1 row per Order)

order_idcustomer_idshipping_fee
101C110.00
102C115.00

True total shipping fee for `C1` = `$10.00 + $15.00 = $25.00`.

Table 2: `order_items` (Grain: 1 row per Item inside an Order)

item_idorder_idproductitem_price
1101Keyboard80.00
2101Mouse30.00
3101USB Cable10.00
4102Monitor250.00

The Broken Query (Fan-Out Bug!)

SELECT
  o.customer_id,
  SUM(o.shipping_fee) AS reported_shipping,
  SUM(i.item_price)   AS reported_items
FROM orders o
JOIN order_items i
  ON o.order_id = i.order_id
GROUP BY o.customer_id;

Look at what the intermediate JOIN builds *before* GROUP BY sums anything:

o.order_ido.shipping_feei.item_idi.item_price
10110.00180.00
10110.00230.00
10110.00310.00
10215.004250.00
  • reported_items = 80 + 30 + 10 + 250 = $370.00 (correct!)
  • reported_shipping = 10 + 10 + 10 + 15 = $45.00 (WRONG! Inflated by $20!)

The Clean Fix: Pre-Aggregate Child Tables First with CTEs

Before joining two tables, make sure their grains match (1 row per order_id on BOTH sides!):

WITH item_totals_by_order AS (
  SELECT
    order_id,
    COUNT(*)        AS item_count,
    SUM(item_price) AS items_subtotal
  FROM order_items
  GROUP BY order_id
)
SELECT
  o.customer_id,
  COUNT(o.order_id)               AS order_count,
  SUM(o.shipping_fee)             AS true_shipping_fee,
  SUM(COALESCE(it.items_subtotal, 0)) AS true_items_total
FROM orders o
LEFT JOIN item_totals_by_order it
  ON o.order_id = it.order_id
GROUP BY o.customer_id;

Output: true_shipping_fee = 25.00, true_items_total = 370.00 — 100% accurate, zero duplication!


Common Beginner Mistakes (And How to Fix Them)

Mistake 1: Turning a `LEFT JOIN` Back into an `INNER JOIN` Accidentally - **Broken:**

SELECT c.customer_name, o.order_id
  FROM customers c
  LEFT JOIN orders o ON c.customer_id = o.customer_id
  WHERE o.status = 'PAID';
  • Why it breaks: Customers with zero orders have o.status = NULL. Putting o.status = 'PAID' in the WHERE clause deletes all unmatched customers!
  • Fix: Move right-table filters inside the `ON` clause:
LEFT JOIN orders o
    ON c.customer_id = o.customer_id
   AND o.status = 'PAID'

Mistake 2: Hiding Fan-Out With `SELECT DISTINCT` Using `SELECT DISTINCT` or `COUNT(DISTINCT ...)` as a band-aid hides deeper join bugs, burns memory on giant sorts, and breaks `SUM()` completely (`SUM(DISTINCT 10.00)` would merge two different `$10` orders into `$10`!). Always fix the grain via CTE pre-aggregation instead.


Quick Cheat Sheet

  1. Verify row counts before and after every JOIN (SELECT COUNT(*)) to spot unexpected fan-out immediately.
  2. Put right-table conditions in `ON` (not WHERE) when using LEFT JOIN.
  3. Never join two 1-to-Many child tables at the same time (the Chasm Trap) — aggregate each child table in its own CTE first.
  4. Use `EXISTS` when you only want to check existence without duplicating left rows.

Comprehension & Architecture Check (3 Questions)

Test your understanding of the concepts covered in this lesson.

1. Order #100 has a $10 shipping fee and 4 line items. What does SUM(o.shipping_fee) return if you join orders directly to order_items?
2. What is the cleanest way to combine two tables with different grains?
3. When should you use LEFT JOIN instead of INNER JOIN between summary CTEs?
Practice What You Learned

FOUNDATIONS-4: The JOIN Fan-Out Trap (Why Revenue Doubled!)

For each customer_id, compute accurate total_shipping (from gold.fact_orders) and total_items_value (from gold.fact_order_items) without inflating shipping_fee! Pre-aggregate shipping per customer in one CTE and item revenue per customer in a second CTE, then join them by customer_id.

Solve Challenge