Join Fan Out Inflates Aggregates
Summing a parent through a one-to-many join counts each parent once per child; pre-aggregate the child side in a CTE to keep totals honest.
Code
WITH orders(id, customer_id, total_cents) AS (
VALUES
(1, 10, 5000),
(2, 10, 3000)
),
refunds(id, order_id, cents) AS (
VALUES
(100, 1, 500),
(101, 1, 700),
(102, 2, 200)
)
-- 直接 JOIN 再聚合:join fan out 把 order 1 放大成两行,
-- 它的 total_cents 被算了两遍(10000 而不是 5000)
SELECT
o.id,
o.total_cents,
SUM(r.cents) AS refund_cents,
SUM(o.total_cents) AS inflated_total
FROM orders o
LEFT JOIN refunds r ON r.order_id = o.id
GROUP BY o.id
ORDER BY o.id;
-- 修正:先按关联键预聚合子表,再关联,父表不再被放大
WITH refund_by_order AS (
SELECT order_id, SUM(cents) AS refund_cents
FROM refunds
GROUP BY order_id
)
SELECT
o.id,
o.total_cents,
COALESCE(r.refund_cents, 0) AS refund_cents,
o.total_cents - COALESCE(r.refund_cents, 0) AS net_cents
FROM orders o
LEFT JOIN refund_by_order r ON r.order_id = o.id
ORDER BY o.id;Inside the snippet
Several statements share this file — SELECT, with orders, refunds and refund_by_order among the objects involved.
Mechanically, the statements are built from: a CTE (WITH … AS) that names an intermediate result before the main query; 2 JOINs combining rows across tables; SUM aggregation; a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order.
What to watch for
- 2 joins multiply the intermediate row count; confirm the join keys are indexed before pointing this at production-sized tables.
Using it
The orders table is the working surface here.
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which objects does the SQL touch?
- The references are `orders`, `refunds`, `refund_by_order`, with 2 joins tying them together.
Report a problem with this exampleOpens a pre-filled issue on GitHub.