Sub topic 9
One-to-many matches and row counts
This chapter assumes you can write a basic INNER JOIN ... ON query and know how primary and foreign keys link tables. It uses the sample customers and orders tables from earlier chapters. The goal is to predict how many rows a join returns before you run it, and to avoid wrong totals when the row count surprises you.
Why the row count changes
An inner join does not return one row per row of the first table. It returns one row for each pair of rows that satisfies the ON condition. If one parent row matches three child rows, the result has three rows for that parent, and the parent's column values are repeated on each of them.
The relationships in the sample schema look like this:
Each ||--o{ link is one-to-many: the side with || is the "one" (parent) and the side with o{ is the "many" (child). Joining across such a link multiplies parent rows by their number of children. Orders and products are many-to-many, and the order_items table sits between them to express that.
Sample data for this chapter
The order_items and products tables were introduced with multi-table joins. If you have not created them yet, run this. It adds items to three of the four orders. Order 104 has none.
CREATE TABLE products (
id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL
);
CREATE TABLE order_items (
order_id INTEGER NOT NULL REFERENCES orders (id),
product_id INTEGER NOT NULL REFERENCES products (id),
quantity INTEGER NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO products (id, name) VALUES
(1, 'Keyboard'), (2, 'Mouse'), (3, 'Monitor');
INSERT INTO order_items (order_id, product_id, quantity) VALUES
(101, 1, 1),
(101, 2, 2),
(102, 3, 1),
(103, 2, 1);Order 101 has two items, orders 102 and 103 have one each, and order 104 has none.
Predicting the row count
For an equality join, you can compute the result size from the key values. For each key value k, multiply the number of rows in the left table that have k by the number of rows in the right table that have k. Add those products across all keys. Keys that appear on only one side contribute zero, and NULL keys never match.
| Left rows with key | Right rows with key | Rows in result |
|---|---|---|
| 1 | 1 | 1 |
| 1 | 3 | 3 |
| 2 | 3 | 6 |
| 1 | 0 | 0 |
The third row of the table is a many-to-many match. When both sides repeat a key, every left row pairs with every right row.
For orders joined to order_items on order_id: order 101 gives 1 × 2 = 2 rows, order 102 gives 1, order 103 gives 1, and order 104 gives 0. The result has 4 rows, even though there are 4 orders and 4 items. Those counts match only by coincidence, because order 104 drops out while order 101 doubles.
You can check the per-order counts yourself:
SELECT o.id AS order_id, COUNT(*) AS joined_rows
FROM orders AS o
INNER JOIN order_items AS i ON i.order_id = o.id
GROUP BY o.id
ORDER BY o.id;This returns 101 with 2, 102 with 1, and 103 with 1. Order 104 is absent.
Seeing the repeated parent values
Here is the join itself:
SELECT o.id AS order_id, o.total, p.name AS product, i.quantity
FROM orders AS o
INNER JOIN order_items AS i ON i.order_id = o.id
INNER JOIN products AS p ON p.id = i.product_id
ORDER BY o.id, p.name;| order_id | total | product | quantity |
|---|---|---|---|
| 101 | 50.00 | Keyboard | 1 |
| 101 | 50.00 | Mouse | 2 |
| 102 | 75.00 | Monitor | 1 |
| 103 | 20.00 | Mouse | 1 |
The total of 50.00 for order 101 appears twice. The order has one total, but the result has one row per item, so the value is copied onto each row. Each result row describes an item, not an order. The row's grain, meaning what one row stands for, changed when you joined to the child table.
Where the numbers go wrong
Aggregate functions work on result rows, not on the original tables. If you join to a child table and then aggregate a parent column, you count the parent once per child.
SELECT SUM(o.total) AS inflated_revenue
FROM orders AS o
INNER JOIN order_items AS i ON i.order_id = o.id;This returns 195.00: 50 + 50 + 75 + 20. The orders that have items sum to 145.00, and all four orders sum to 244.00. The query is wrong for either meaning, and it runs without any error.
COUNT has the same problem:
SELECT COUNT(*) AS joined_rows,
COUNT(DISTINCT o.id) AS orders_with_items
FROM orders AS o
INNER JOIN order_items AS i ON i.order_id = o.id;This returns 4 and 3. COUNT(*) counts joined rows, which are items here. COUNT(DISTINCT o.id) counts orders that have at least one item.
Fixes for double counting
You have three common options, and the right one depends on what you need.
- Aggregate a child column.
SUM(i.quantity)is safe becausequantitybelongs to the item rows, which are the grain of the join. - Count distinct parents.
COUNT(DISTINCT o.id)removes the repeats for counting. It is not a safe fix for sums.SUM(DISTINCT o.total)collapses two different orders that happen to have the same total. - Aggregate the child first, then join. Reduce the child table to one row per parent in a subquery, then join that to the parent. The join is now one-to-one, so nothing repeats.
The third option looks like this. It returns each order's total next to its item count and units without inflating anything:
SELECT o.id AS order_id, o.total, s.item_count, s.units
FROM orders AS o
INNER JOIN (
SELECT order_id,
COUNT(*) AS item_count,
SUM(quantity) AS units
FROM order_items
GROUP BY order_id
) AS s ON s.order_id = o.id
ORDER BY o.id;Each order appears once: 101 has 2 items and 3 units, 102 has 1 and 1, 103 has 1 and 1. Because s has one row per order_id, SUM(o.total) over this result is safe too. It returns 145.00, the total for orders that have items.
Two child tables at once
Row multiplication compounds when you join one parent to two independent child tables. Suppose each order also had a shipments table. An order with 2 items and 3 shipments produces 2 × 3 = 6 rows, because the database pairs every item with every shipment. Sums of either child's columns are then too large. The fix is the same as above: aggregate each child to one row per parent in its own subquery, then join the results.
A quick checklist
- Name the grain of the result: one row per what?
- Check each join link: is it one-to-one, one-to-many, or many-to-many?
- Compare
COUNT(*)withCOUNT(DISTINCT parent_key). If they differ, rows are being repeated. - Compare your total with a query on the parent table alone.
Exercise
Using the sample data, how many rows does SELECT * FROM orders AS o INNER JOIN order_items AS i ON i.order_id = o.id WHERE o.customer_id = 1 return, and what does SUM(o.total) give for that query? What is Ada's real order total, and how would you compute it correctly?
Show answer
Ada owns orders 101 and 102. Order 101 has 2 items and order 102 has 1, so the join returns 3 rows. SUM(o.total) gives 50 + 50 + 75 = 175.00, because order 101's total is counted once per item. Ada's real total is 50 + 75 = 125.00. Compute it correctly with SELECT SUM(total) FROM orders WHERE customer_id = 1 with no join. If you need item data in the same query, aggregate order_items per order in a subquery first and join that to orders.