hangoolconsulting.com

SQL

Why a SQL join can change your totals

Follow a $30 order through a one-to-many join, then use a grouped query to get the original revenue total back.

A thread connects two groups of punched index cards.

Order 104 is worth $30 and contains three line items. Your orders report shows $30. You add item details to the query and the report suddenly shows $90 for the same order. The clue is in what each row represents.

Follow one order through the join

Imagine two orders. Order 104 totals $30 and has three items. Order 105 totals $20 and has one item. The orders table has two rows and its total is $50. A join to the items table matches each order to every item carrying its ID.

OrderOrder totalItem
104$30A
104$30B
104$30C
105$20D

The joined result correctly describes four items. The order total is repeated on each matching row, so summing that column gives $110. The question “How many items are there?” and the question “What is the order revenue?” need different units of analysis.

Check how many rows each key produces

Start with a small range of orders you can verify manually. This query shows orders with several matching item rows. On this example it returns order 104 with three matches.

SELECT o.order_id, COUNT(*) AS joined_rows
FROM orders AS o
JOIN order_items AS i ON i.order_id = o.order_id
GROUP BY o.order_id
HAVING COUNT(*) > 1;

Several matches are expected when the relationship is one order to many items. If you expected one match, inspect the key. Two lines for one order may be entirely legitimate, while two rows with the same item ID may point to a duplicate upstream.

Bring the items to one row per order

For a report that needs both revenue and item counts, group the items by order first. Then join that smaller result to orders. A left join also keeps an order whose items have not arrived in the export.

WITH items_per_order AS (
    SELECT order_id, COUNT(*) AS item_count
    FROM order_items
    GROUP BY order_id
)
SELECT o.order_id, o.order_total,
       COALESCE(i.item_count, 0) AS item_count
FROM orders AS o
LEFT JOIN items_per_order AS i
       ON i.order_id = o.order_id;

The output now contains order 104 with $30 and three items, and order 105 with $20 and one item. Summing the two order totals gives $50. This assumes the orders table itself has one row per order ID.

Test a case that could fool you

Add another order worth $30. The correct revenue rises to $80. A shortcut such as SUM(DISTINCT order_total) would count the two $30 amounts only once. Unique amounts and unique orders answer different questions. Use the order ID to control the level of the report.

PostgreSQL documentation on joined tables and grouping