← All lessons
Combining and summarizing · Lesson 6 of 10

Joining several tables

An order can hold many products, and a product can be in many orders. A database can't put a list in one cell, so order_items sits between them: one row per product per order, with a foreign key to each side and the quantity. A table like that is called a linking table (or bridge table). To go from an order to its products, you join through it:

SELECT o.id AS order_id, p.name, i.qty
FROM orders o
JOIN order_items i ON i.order_id = o.id
JOIN products p ON p.id = i.product_id
WHERE o.customer_id = 1
ORDER BY o.id, p.name;
Returns
order_id | name        | qty
---------+-------------+----
101      | Duck feeder | 1
101      | Pond net    | 2
103      | Field guide | 1
103      | Sketchbook  | 3
108      | Sketchbook  | 1
(5 rows)

Each JOIN adds one table. With the price joined in, i.qty * p.price is the line total, and grouping by order adds the lines up:

SELECT i.order_id, SUM(i.qty * p.price) AS total
FROM order_items i
JOIN products p ON p.id = i.product_id
GROUP BY i.order_id
ORDER BY total DESC
LIMIT 3;
Returns
order_id | total
---------+------
105      | 93.5
110      | 81.5
107      | 80
(3 rows)

Joins multiply rows, and that's the thing to watch. Ana has 3 orders; joined to order_items she has 5 rows, one per item. That's right for adding up items, but if you now count her orders with COUNT(*) you get 5, not 3. Before writing a join, ask "one row per what?". After it, check the row count. COUNT(DISTINCT o.id) counts each order once however many items it has:

SELECT c.name, COUNT(*) AS item_rows, COUNT(DISTINCT o.id) AS orders
FROM customers c
JOIN orders o ON o.customer_id = c.id
JOIN order_items i ON i.order_id = o.id
WHERE c.id = 1
GROUP BY c.id, c.name;
Returns
name | item_rows | orders
-----+-----------+-------
Ana  | 5         | 3
(1 row)

The same goes for sums. If orders had a delivery fee and you added up o.delivery_fee after joining the items, each order's fee would be counted once per item. Add up order-level numbers before joining, or from orders alone.

Practice

What's in order 105: each product's name and the qty.

The tables
  • customers (id, name, city, joined)
  • products (id, name, category, price)
  • orders (id, customer_id, ordered_on, status)
  • order_items (order_id, product_id, qty)
  • signups (id, email, name, signed_up_at)
  • payments (id, order_id, amount, currency, paid_at)
  • events (id, received_at, payload (JSON text))
  • staff (id, name, role, manager_id, salary, hired)
  • logins (customer_id, day)
More info

Quick reference

linking tableOne row per pair (order_items: order and product).
JOIN … JOIN …Each join adds a table.
SUM(i.qty * p.price)Line totals added up.
one row per what?Ask before joining; check the row count after.
COUNT(DISTINCT o.id)Count each order once after a join that multiplied rows.

The other AI and data engineering courses