Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Performance & internals
Stage 5: Specialization

Part 05 / Topic 6 of 9

Three and more tables

Joins chain. Each JOIN ... ON bolts one more table onto the working set, and the query stays readable if you add them in foreign-key order. The classic shopdb question — revenue per category, counting only delivered orders:

SELECT cat.name AS category,
       sum(oi.quantity * oi.unit_price) AS revenue
FROM order_items AS oi
JOIN orders     AS o   ON o.order_id = oi.order_id
JOIN products   AS p   ON p.product_id = oi.product_id
JOIN categories AS cat ON cat.category_id = p.category_id
WHERE o.status = 'delivered'
GROUP BY cat.name
ORDER BY revenue DESC;
 category | revenue 
----------+---------
 Laptops  | 2400.00
 Phones   | 1198.00
 Books    |  340.00
 Kitchen  |   80.00
 Home     |   45.00
(5 rows)

Four tables, one number per category. Read it the way Postgres logically does: start from the order lines, attach each line's order (for the status), its product, and the product's category; filter, group, sum. Stage 1's whole toolkit — WHERE, GROUP BY, ORDER BY — carries over untouched; joins only changed what FROM produces.

Start every multi-join at the fact table (the one holding the numbers — here order_items) and join outward to the descriptions. That habit scales to ten tables.

🧪 Quick quiz — answer from memory, then check.

  1. In the query above, why does the WHERE need the orders table at all?
  2. Where do WHERE and GROUP BY go in a multi-table join?
Show the answers
  1. status lives on orders, not on the order lines — the join brings it within reach.
  2. Exactly where they always went — after the (now bigger) FROM. Joins extend FROM; the rest of the query is unchanged.

Done here? The practice set for Part 5 — 8 exercises with solutions — is on the part page.

Search the guide