Joining many tables

Topic 4 of 4 in Joining tables11 min readBeginnerFree course

Overview

Real questions often cross the whole schema: which customers in India bought tea? needs customers, orders, order items, products and categories — five tables. Joining many tables is no harder than joining two; you just add one join at a time. But two new problems appear with long joins, and both produce wrong answers without errors: outer joins that quietly turn inner, and fan-out that double-counts. This lesson shows how to spot and avoid both.

A five-table join

Joining many tables. A chain of five tables: customers AS c, orders AS o, order_items AS oi, products AS p and categories AS cat, connected by o.customer_id = c.id, oi.order_id = o.id, p.id = oi.product_id and cat.id = p.category_id. The query is SELECT c.first_name, o.id AS order_id, p.name AS product, cat.name AS category, oi.quantity FROM customers AS c JOIN orders AS o ON o.customer_id = c.id JOIN order_items AS oi ON oi.order_id = o.id JOIN products AS p ON p.id = oi.product_id LEFT JOIN categories AS cat ON cat.id = p.category_id. Each JOIN adds one table, connected by its key; follow the foreign keys in the schema diagram to know what to write. Use LEFT JOIN for links that may be missing — here a product may have no category.

Here’s the chain from the diagram, for Asha’s orders:

SQL
SELECT c.first_name,
       o.id        AS order_id,
       p.name      AS product,
       cat.name    AS category,
       oi.quantity
FROM customers AS c
JOIN orders AS o            ON o.customer_id = c.id
JOIN order_items AS oi      ON oi.order_id = o.id
JOIN products AS p          ON p.id = oi.product_id
LEFT JOIN categories AS cat ON cat.id = p.category_id
WHERE c.id = 1
ORDER BY o.id, p.name;
Text
 first_name | order_id |        product         | category  | quantity 
------------+----------+------------------------+-----------+----------
 Asha       |        1 | Assam Breakfast        | Tea       |        1
 Asha       |        1 | Ethiopian Yirgacheffe  | Coffee    |        2
 Asha       |        3 | Darjeeling First Flush | Tea       |        1
 Asha       |        9 | Electric Kettle        | Equipment |        1
 Asha       |        9 | Jasmine Green          | Tea       |        1
 Asha       |       17 | Ethiopian Yirgacheffe  | Coffee    |        3
 Asha       |       23 | Assam Breakfast        | Tea       |        2
 Asha       |       23 | Ethiopian Yirgacheffe  | Coffee    |        2
(8 rows)

Each JOIN attaches one more table to what’s been built so far, and each ON names the key that links it. The order of the joins mostly doesn’t matter to the result — the database chooses its own execution order — but writing them in the order of the relationships (customer → order → item → product → category) makes the query easy to follow.

The last join is a LEFT JOIN because a product may have no category. Asha hasn’t bought one, but two other orders include a gift card, which has no category — with an inner join to categories, those lines would vanish from any report built on this query.

Build it step by step

Long joins are easiest to get right incrementally. Start with the first table and check how many rows there are, then add one join at a time and think about whether the new count makes sense:

SQL
SELECT count(*) FROM orders WHERE customer_id = 1;
Text
 count 
-------
     5
(1 row)
SQL
SELECT count(*)
FROM orders AS o
JOIN order_items AS oi ON oi.order_id = o.id
WHERE o.customer_id = 1;
Text
 count 
-------
     8
(1 row)

Five orders became eight rows: one per item. That’s expected — an order has one or more items. If adding products changed the count again, something would be wrong, because every item has exactly one product. Knowing which joins should keep the count (many-to-one, like item → product) and which should grow it (one-to-many, like order → items) is the best bug detector you have.

Keeping outer joins outer

When a table is joined with LEFT JOIN, its columns can be NULL. If a later join connects to that table with an inner JOIN, those NULL rows can’t match and are thrown away — undoing the outer join.

Every customer, with how many order lines they’ve bought — including customers who’ve bought nothing:

SQL
SELECT c.first_name, count(p.id) AS lines_bought
FROM customers AS c
LEFT JOIN orders AS o       ON o.customer_id = c.id
JOIN order_items AS oi      ON oi.order_id = o.id
JOIN products AS p          ON p.id = oi.product_id
GROUP BY c.id, c.first_name
ORDER BY c.first_name;
Text
 first_name | lines_bought 
------------+--------------
 Asha       |            8
 Ben        |            7
 Chen       |            4
 Dee        |            4
 Elena      |            6
 Farhan     |            5
 Grace      |            5
 Hugo       |            3
(8 rows)

Isha and Jack have vanished. The LEFT JOIN kept them with NULL o.id, but the next inner join required oi.order_id = o.id, which NULL can’t satisfy. The rule: once you go LEFT, stay LEFT for everything that hangs off that table:

SQL
SELECT c.first_name, count(p.id) AS lines_bought
FROM customers AS c
LEFT JOIN orders AS o       ON o.customer_id = c.id
LEFT JOIN order_items AS oi ON oi.order_id = o.id
LEFT JOIN products AS p     ON p.id = oi.product_id
GROUP BY c.id, c.first_name
ORDER BY c.first_name;
Text
 first_name | lines_bought 
------------+--------------
 Asha       |            8
 Ben        |            7
 Chen       |            4
 Dee        |            4
 Elena      |            6
 Farhan     |            5
 Grace      |            5
 Hugo       |            3
 Isha       |            0
 Jack       |            0
(10 rows)

Everyone is back, with zeros where they belong.

The fan-out trap

This one catches experienced people. How much did each customer pay for shipping, and how much for items? The obvious query:

SQL
SELECT c.first_name,
       sum(o.shipping_fee)              AS shipping,
       sum(oi.quantity * oi.unit_price) AS items
FROM customers AS c
JOIN orders AS o       ON o.customer_id = c.id
JOIN order_items AS oi ON oi.order_id = o.id
WHERE c.id IN (2, 3)
GROUP BY c.id, c.first_name
ORDER BY c.first_name;
Text
 first_name | shipping | items  
------------+----------+--------
 Ben        |    45.50 | 285.25
 Chen       |    32.00 | 123.75
(2 rows)

The items total is right, but the shipping is wrong. Compare with the orders table alone:

SQL
SELECT customer_id, sum(shipping_fee) AS shipping
FROM orders
WHERE customer_id IN (2, 3)
GROUP BY customer_id
ORDER BY customer_id;
Text
 customer_id | shipping 
-------------+----------
           2 |    26.00
           3 |    24.00
(2 rows)

What happened? After joining order_items, every order appears once per item. An order with two items repeats its shipping_fee on both rows, and sum adds it twice. This is called fan-out: joining a “one” table to a “many” table fans each parent row out, and any sum or count of the parent’s columns is inflated. It’s dangerous because the result looks plausible.

There are two reliable fixes.

1. Aggregate the child table before joining. Collapse order_items to one row per order first, so the join is one-to-one again:

SQL
SELECT c.first_name,
       sum(o.shipping_fee) AS shipping,
       sum(t.items_total)  AS items
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.id
JOIN (SELECT order_id, sum(quantity * unit_price) AS items_total
      FROM order_items
      GROUP BY order_id) AS t ON t.order_id = o.id
WHERE c.id IN (2, 3)
GROUP BY c.id, c.first_name
ORDER BY c.first_name;
Text
 first_name | shipping | items  
------------+----------+--------
 Ben        |    26.00 | 285.25
 Chen       |    24.00 | 123.75
(2 rows)

Both totals are now right. The bracketed query in the FROM is a subquery — a query used as a table — and it’s the subject of the next chapter.

2. Only aggregate at the level you joined to. If you need counts of parents after a fan-out, count(DISTINCT o.id) counts each order once. (sum(DISTINCT shipping_fee) is not a fix — two different orders with the same fee would be counted once.)

Many joins, one question

With these habits, a question that spans the whole schema is straightforward. Units of each category bought by customers in India, ignoring cancelled orders:

SQL
SELECT COALESCE(cat.name, 'No category') AS category,
       sum(oi.quantity)                  AS units,
       count(DISTINCT o.id)              AS orders,
       string_agg(DISTINCT c.first_name, ', ') AS customers
FROM customers AS c
JOIN orders AS o            ON o.customer_id = c.id
JOIN order_items AS oi      ON oi.order_id = o.id
JOIN products AS p          ON p.id = oi.product_id
LEFT JOIN categories AS cat ON cat.id = p.category_id
WHERE c.country = 'India'
  AND o.status <> 'cancelled'
GROUP BY cat.name
ORDER BY units DESC;
Text
 category  | units | orders |  customers   
-----------+-------+--------+--------------
 Tea       |    12 |      6 | Asha, Farhan
 Coffee    |     7 |      3 | Asha
 Equipment |     1 |      1 | Asha
(3 rows)

count(DISTINCT o.id) counts orders correctly despite the fan-out to items, and string_agg(DISTINCT …) lists each customer once.

Checklist for long joins: (1) write joins in the order of the relationships; (2) check the row count after each one; (3) once a table is LEFT JOINed, LEFT JOIN everything hanging off it; (4) never sum a parent’s column after joining its children — aggregate the children first.

Exercise

Revenue by country

Which countries buy the most? Join customers, orders and order_items to calculate, for each customer country, the number of distinct orders and the revenue from order items (quantity × unit price), ignoring cancelled orders. Sort by revenue, highest first.

SQL
SELECT c.country
FROM customers AS c
JOIN orders AS o ON o.customer_id = c.id
-- join order_items, filter, group and sum

Summary

  • Each JOIN adds one table, connected by its key; follow the foreign keys in the schema to know what to write.
  • Build long joins one table at a time and check the row count after each step.
  • Once a table is LEFT JOINed, later joins to it usually need to be LEFT JOINs too, or the missing rows disappear again.
  • Joining a parent to a child table repeats the parent's columns on every child row — summing a parent column then double-counts (fan-out).
  • Fix fan-out by aggregating the child table first, or by summing only at the right level, and use count(DISTINCT …) to count parents.