Two 1:N joins: fan-out and conditional aggregation

Computing VIP customers' 2024 and 2025 sales by joining the same orders table twice produces (2024 orders × 2025 orders) rows per customer. One high-volume customer makes the intermediate result 430,000 rows, and the totals inflate by hundreds of times and become wrong. The fix is conditional aggregation that reads the orders only once.

SQL

Situation

A report compares yearly sales for 1,000 VIP customers. To show 2024 sales and 2025 sales in one row, the orders table was joined twice, once per year. The report is slow, and the sales team also reported that "customer 100's sales look oddly large". Customer 100 is a high-volume B2B customer.

Tables

TableColumnsDescription
customersgrade, cust_nm1,000 VIPs
orderscust_id, ord_dt, amtCustomer 100 has 735 orders in 2024 and 540 in 2025. Other VIPs have a few per year
IndexColumns
customers_x1grade
orders_x1cust_id, ord_dt

Query

BEFORE · Orders joined twice, once per year

SELECT c.cust_id, c.cust_nm,
       SUM(o24.amt) AS amt_2024,
       SUM(o25.amt) AS amt_2025
FROM customers c
JOIN orders o24 ON o24.cust_id = c.cust_id
               AND o24.ord_dt >= TIMESTAMP '2024-01-01'
               AND o24.ord_dt <  TIMESTAMP '2025-01-01'
JOIN orders o25 ON o25.cust_id = c.cust_id
               AND o25.ord_dt >= TIMESTAMP '2025-01-01'
               AND o25.ord_dt <  TIMESTAMP '2026-01-01'
WHERE c.grade = 'VIP'
GROUP BY c.cust_id, c.cust_nm
ORDER BY c.cust_id

Check whether the result count equals the 1,000 VIPs, and how many rows come up under HashAggregate.

Approach

1. Compute the row count of the join result

If one customer has a orders in 2024 and b orders in 2025, the two joins are unrelated to each other, so that customer gets a × b rows. A typical VIP is around 7 × 5 and goes unnoticed, but customer 100 is 735 × 540 = 396,900 rows. This is called fan-out. It occurs when two or more 1:N relationships hang off one table.

2. Check whether the aggregate values are correct

Computing SUM(o24.amt) over a × b rows adds each 2024 order b times. Being wrong comes before being slow. Also, because these are inner joins, customers with no orders in either 2024 or 2025 drop out of the result.

3. Check whether the same table can be read only once

The two joins are different periods of the same table. Read the combined range of both periods once, and add each row to a different total depending on its year. Alternatively, aggregate each period per customer first so there is one row per customer, then join. Either way, there must be "one row per customer before the join" to avoid fan-out.

Explanation

Read orders once with conditional aggregation

AFTER · Conditional aggregation

SELECT c.cust_id, c.cust_nm,
       SUM(CASE WHEN o.ord_dt <  TIMESTAMP '2025-01-01' THEN o.amt END) AS amt_2024,
       SUM(CASE WHEN o.ord_dt >= TIMESTAMP '2025-01-01' THEN o.amt END) AS amt_2025
FROM customers c
JOIN orders o ON o.cust_id = c.cust_id
             AND o.ord_dt >= TIMESTAMP '2024-01-01'
             AND o.ord_dt <  TIMESTAMP '2026-01-01'
WHERE c.grade = 'VIP'
GROUP BY c.cust_id, c.cust_nm
ORDER BY c.cust_id

Why it got faster (and why it is now correct)

  • Before is two levels of Nested Loop. For each of the 1,000 VIPs it finds the 2025 orders (5,387 rows), and for each of those rows it finds the 2024 orders again (Starts 5,387). The join result is 429,505 rows, of which 396,900 belong to customer 100. Buffers 456,090. The result has 993 rows: 7 VIPs with no orders in one of the two years are missing.
  • After reads the orders table only once (Seq Scan, 18,752 blocks) and hash-joins it with the VIP customers. The join result is 12,834 rows, the same as the number of orders, and all 1,000 customers appear. Buffers 19,589.
  • Customer 100's 2024 total is about 97 billion in Before and about 180 million in After. That is the 735 orders of 2024 added repeatedly as many times as the number of 2025 orders (540). The 2025 total is inflated 735 times.

Why this is optimal

  • The join result now equals "the number of orders that must be read". The two-year order range is 64% of the table (1.27 million rows), so reading it all once is cheaper than looking up each customer through the index.
  • The remaining cost is one full table read. Without changing the table structure, there is no way to read two years of VIP customer orders for less.

Variation: see the wrong values

TRY · Customers 100, 200 (joined twice)

SELECT c.cust_id,
       SUM(o24.amt) AS amt_2024, SUM(o25.amt) AS amt_2025,
       COUNT(DISTINCT o24.ord_id) AS cnt_2024, COUNT(DISTINCT o25.ord_id) AS cnt_2025,
       COUNT(*) AS joined_rows
FROM customers c
JOIN orders o24 ON o24.cust_id = c.cust_id
               AND o24.ord_dt >= TIMESTAMP '2024-01-01' AND o24.ord_dt < TIMESTAMP '2025-01-01'
JOIN orders o25 ON o25.cust_id = c.cust_id
               AND o25.ord_dt >= TIMESTAMP '2025-01-01' AND o25.ord_dt < TIMESTAMP '2026-01-01'
WHERE c.cust_id IN (100, 200)
GROUP BY c.cust_id
ORDER BY c.cust_id
  • Check that joined_rows equals cnt_2024 × cnt_2025. For customer 100 it is 396,900.

Variation: aggregate, then join

TRY · Aggregate per period, then join

SELECT c.cust_id, c.cust_nm, o.amt_2024, o.amt_2025
FROM customers c
JOIN (
  SELECT cust_id,
         SUM(CASE WHEN ord_dt <  TIMESTAMP '2025-01-01' THEN amt END) AS amt_2024,
         SUM(CASE WHEN ord_dt >= TIMESTAMP '2025-01-01' THEN amt END) AS amt_2025
  FROM orders
  WHERE ord_dt >= TIMESTAMP '2024-01-01' AND ord_dt < TIMESTAMP '2026-01-01'
  GROUP BY cust_id
) o ON o.cust_id = c.cust_id
WHERE c.grade = 'VIP'
ORDER BY c.cust_id
  • The result is the same as After, and Buffers are the same 19,589. But HashAggregate aggregates all 99,997 customers, not just the VIPs, and then uses only the 1,000 VIPs in the join (14MB of memory). This is because PostgreSQL does not push the outer join condition into the aggregate view. Aggregate-then-join pays off when the aggregation target is already narrowed. For Oracle's join predicate pushdown, see Oracle scenario 18.

Key points

  • Joining two 1:N relationships to one table at the same time produces N × M rows. The aggregates are wrong, and the intermediate result grows in proportion to the square of the largest group. One high-volume customer slows down the whole report.
  • Different periods of the same table are read at once with conditional aggregation (SUM(CASE WHEN …), or SUM(amt) FILTER (WHERE …) in PostgreSQL).
  • For different child tables, aggregate each into one row per parent key first, then join.
  • "Fixing" the result with COUNT(DISTINCT …) or DISTINCT is not the answer. It can fix the counts but not the totals, and the size of the intermediate result stays the same.