SQL query & grain correctness guide
Joins, CTEs, window functions, and preventing chasm traps.
Executed experiment / SQL
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
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.
Orders: (1,100), (2,50). Detail lines: (1,1), (2,1), (3,2), represented as line ID and order ID.
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
Execute both SQL queries in the embedded PostgreSQL engine. Compare a direct join sum with an EXISTS-filtered sum at order grain.
-- 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.
-- 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.
-- 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.
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.
| Order ID | Line ID | Header amount (o.amount) | Included in naive SUM? | Contribution to naive total |
|---|---|---|---|---|
| 1 | 1 | 100 | Yes (row 1 of Order 1) | 100 |
| 1 | 2 | 100 | Yes (row 2 of Order 1 — duplicated) | 100 |
| 2 | 3 | 50 | Yes (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: Join sum: 250. Order-grain sum: 150.
Actual: Executed join sum: 250. Executed order-grain sum: 150.
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.
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.
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.
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:
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.
Joins, CTEs, window functions, and preventing chasm traps.
Handling multi-grain fact tables cleanly in semantic models.
Another common aggregation trap: unweighted means vs. weighted ratios.
Test denominator sensitivity interactively in your browser.
Inspect how in-process PostgreSQL experiments are verified.
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.