Skip to content

Executed experiment / SQL

Why a detail join can inflate an order total

Does summing an order-level amount after joining detail lines preserve its grain?

By Datta Sable · Published · Version 1 · Synthetic data · No peer review claimed

Why this failure mode matters in production BI

Fan-out join inflation (also called a chasm trap or grain mismatch) is one of the most expensive silent bugs in SQL reporting and BI semantic models. Because the query executes without syntax errors and returns a plausible positive number, inflated revenue, duplicated freight charges, or double-counted loan balances can survive in production scorecards for months.

The root cause is mixing two different table grains in the same FROM/JOIN clause before aggregating. An orders table has one row per order_id, whereas an order_lines table has one row per line_id (many lines per order). Joining them multiplies every order-header attribute—such as order_total, shipping_fee, or discount_amount—by the number of detail lines belonging to that order.

Analysts sometimes attempt a quick patch using SUM(DISTINCT o.amount), which fails catastrophically as soon as two distinct orders happen to have the exact same monetary value (for example, two $100 subscriptions collapse into $100 instead of $200). The only reliable fix is to aggregate or filter at the grain of the measure being summed.

Dataset and assumptions

Orders: (1,100), (2,50). Detail lines: (1,1), (2,1), (3,2), represented as line ID and order ID.

Download complete fixtures and recorded results (JSON)

Environment

Executed at using v24.15.0 and the installed PGlite PostgreSQL engine. This is an in-process SQL experiment, not connected production database verification.

PostgreSQL 18.7 (PGlite 0.5.17) on wasm32-unknown-emscripten, compiled by emcc (Emscripten gcc/clang-like replacement + linker emulating GNU ld) 6.0.13 (e13ee988ce3d87a738dd8f3661d02223308c412a), 32-bit

Method and executable examples

Execute both SQL queries in the embedded PostgreSQL engine. Compare a direct join sum with an EXISTS-filtered sum at order grain.

Naive SQL (produces inflated grain: 250)

-- BUG: Header amount is multiplied by child line count
SELECT SUM(o.amount) AS naive_total
FROM orders o
JOIN lines l ON l.order_id = o.id;

Never sum a parent-grain column after a 1-to-many join without first reducing the child table to 1 row per parent key.

Order-grain SQL with EXISTS (preserves grain: 150)

-- CORRECT: Filter existence without multiplying parent rows
SELECT SUM(o.amount) AS order_grain_total
FROM orders o
WHERE EXISTS (
  SELECT 1
  FROM lines l
  WHERE l.order_id = o.id
);

EXISTS evaluates to true/false per order row and never duplicates the outer table, regardless of how many matching lines exist.

Pre-aggregated CTE pattern (when you also need line-level metrics)

-- CORRECT: Reduce child table to parent grain before joining
WITH line_summary AS (
  SELECT
    order_id,
    COUNT(*) AS line_count
  FROM lines
  GROUP BY order_id
)
SELECT
  SUM(o.amount) AS order_grain_total,
  SUM(ls.line_count) AS total_lines
FROM orders o
JOIN line_summary ls ON ls.order_id = o.id;

When a dashboard needs both order-level amounts and line-level counts in one query, pre-aggregate the child table to order_id first so the join becomes 1-to-1.

Worked BI scenario: Order-header revenue joined to order-line fulfillment

Suppose a finance analyst wants to calculate total revenue for orders that have at least one fulfilled line item. Order 1 has an order_amount of 100 and 2 detail lines; Order 2 has an order_amount of 50 and 1 detail line. The true order-level revenue is 100 + 50 = 150.

Row-level expansion produced by joining orders (header grain) to lines (detail grain)
Order IDLine IDHeader amount (o.amount)Included in naive SUM?Contribution to naive total
11100Yes (row 1 of Order 1)100
12100Yes (row 2 of Order 1 — duplicated)100
2350Yes (row 1 of Order 2)50

In the joined intermediate result set, Order 1 appears twice because it has two child rows in lines. Summing o.amount over that joined result produces 250 instead of 150—a 66.7% overstatement on this tiny two-order fixture.

In real enterprise warehouses—such as joining invoice headers to payment installments, shipments to tracking events, or CRM opportunities to activity logs—the inflation factor scales with average child cardinality. An order with 12 SKUs inflates header shipping cost by 12×.

Expected and actual results

Expected: Join sum: 250. Order-grain sum: 150.

Actual: Executed join sum: 250. Executed order-grain sum: 150.

Interpretation

Order 1 appears twice after joining two lines. EXISTS selects orders with lines while preserving one row per order. SUM(DISTINCT amount) is not a general repair because different orders may share the same amount.

Production prevention checklist

  • Verify row counts before and after every JOIN: Check COUNT(*) of your base fact table before joining dimensions or bridge tables. If row count increases unexpectedly, you have introduced a fan-out join.
  • Never patch fan-out inflation with SUM(DISTINCT amount): Distinct on a measure collapses legitimate separate transactions that happen to share the same dollar amount. Deduplicate by primary key or aggregate at the true grain instead.
  • Use EXISTS or pre-aggregated CTEs for semi-joins: When you only need to know whether child records exist (e.g., orders with shipments, accounts with active tickets), use WHERE EXISTS rather than an INNER JOIN.
  • Enforce 1-to-many star schema direction in Power BI: Keep header-level measures in a header fact or bridge-free star schema, and avoid bi-directional cross-filtering between two fact tables at different grains.

Limitations

Two orders and three lines establish this counterexample only. Amounts use integer units. No null, currency, tax, missing-order, query-plan or throughput claim is tested.

Reproduce

From the repository, run node scripts/run-engineering-experiments.mjs. The command creates its own ephemeral SQL database, asserts the expected answers, writes data/research/verified-experiments.json and closes the database. It does not read DATABASE_URL or connect to external services.

Applying this experiment to CI/CD & team code reviews

Isolated SQL and data-quality experiments only pay dividends when teams turn them into repeatable review gates. When you review a pull request that modifies a warehouse view, a Power Query transformation, or a DAX semantic measure, ask three concrete verification questions modeled after this study:

  • What is the invariant key before and after each join? Confirm that row counts and distinct primary-key counts match expectations before aggregating downstream totals, avoiding silent 1-to-many fan-outs.
  • Were edge-case rows tested beyond the first 100 records? Verify that null foreign keys, zero denominators, and unexpected string formats trigger explicit data quality quarantine alerts rather than being dropped silently by sampled profiling.
  • Do ratio metrics aggregate from raw numerators and denominators? Cross-check any rate, margin, or completion percentage in the Weighted KPI Lab so executive totals in Power BI and Microsoft Fabric never average unweighted group rates.

To explore how these verification habits carry into full-scale delivery, inspect our engineering standards, check live system architectures in the project portfolio, or review our trust and verification commitments.

Related knowledge paths & engineering labs

References and revision

PostgreSQL table expressions and joins · PGlite documentation · Related learning path · All reproducible studies

Sable, Datta (2026). Why a detail join can inflate an order total. Version 1. https://dattasable.com/research/sql-join-aggregation

6 December 2026: initial fixture, executed results, worked BI examples, and prevention checklist. Report a correction.