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

Part 05 / Stage 2

Joining tables

Goal: Combine related tables correctly — every join type, when each one keeps or drops rows, how row counts multiply, and the handful of pitfalls that produce silently wrong numbers. Time: ~2 hours

What you will learn

  • Why data is split across tables in the first place
  • INNER JOIN: matching rows, and aliases that keep queries readable
  • LEFT JOIN (and RIGHT): keeping unmatched rows, and where NULLs come from
  • FULL OUTER JOIN for finding differences, CROSS JOIN for combinations
  • Self joins: employees and their managers
  • Joining three and more tables
  • The two pitfalls: row multiplication, and ON vs WHERE on outer joins
  • USING, and why NATURAL JOIN is risky
  • Semi-joins and anti-joins: "has one" and "has none"

Everything runs on shopdb. Drifted? psql -d shopdb -f shopdb.sql.

Topics in this part

Practice

SQL workbench — write and run queries here

Press Run and PostgreSQL loads right in your browser (a one-time download of about 16 MB; after that it works offline). It comes seeded with shopdb, and statements share one session per page — like a psql window. Reset data rebuilds shopdb. Your queries never leave this page. Lessons were captured on PostgreSQL 17; the in-browser server is PostgreSQL 19 (via PGlite), so the rare output detail can differ.

Try each one yourself first, in psql against shopdb. Then check the solution.


Exercise 1: Orders with faces

What to do: Every order with the customer's first name and city beside its date and status, in order-id order. (Whose city is blank, and why?)

Sample output:

 order_id | first_name |  city   | order_date |  status   
----------+------------+---------+------------+-----------
        1 | Asha       | Pune    | 2025-01-10 | delivered
        2 | Ravi       | Delhi   | 2025-01-25 | delivered
        3 | Asha       | Pune    | 2025-02-14 | delivered
        4 | Meera      | Chennai | 2025-02-20 | shipped
        5 | John       | London  | 2025-03-05 | cancelled
        6 | Ravi       | Delhi   | 2025-03-18 | delivered
        7 | Asha       | Pune    | 2025-03-30 | pending
        8 | Meera      | Chennai | 2025-04-12 | delivered
        9 | Sara       |         | 2025-04-20 | delivered
(9 rows)

💡 Hint: plain JOIN on customer_id. Sara's blank city is her NULL from Part 3 — joins carry NULLs along untouched.


Show the solution to Exercise 1
-- Exercise 1: Orders with faces
SELECT o.order_id, c.first_name, c.city, o.order_date, o.status
FROM orders AS o
JOIN customers AS c ON c.customer_id = o.customer_id
ORDER BY o.order_id;

Exercise 2: Order count per customer — zeroes included

What to do: One row per customer with how many orders they've placed, busiest first — and the customer with none must appear with 0, not vanish.

Sample output:

 first_name | orders 
------------+--------
 Asha       |      3
 Meera      |      2
 Ravi       |      2
 John       |      1
 Sara       |      1
 Vikram     |      0
(6 rows)

💡 Hint: LEFT JOIN, then count o.order_id (not *) — the NULL-padded row must count as zero.


Show the solution to Exercise 2
-- Exercise 2: Order count per customer, zeroes included
-- count(o.order_id) — not count(*) — so Vikram's NULL-padded row counts 0.
SELECT c.first_name, count(o.order_id) AS orders
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.customer_id
GROUP BY c.customer_id, c.first_name
ORDER BY orders DESC, c.first_name;

Exercise 3: Shelf warmers

What to do: Which products have never been ordered? Write it twice: once as a LEFT JOIN anti-join, once with NOT EXISTS.

Sample output (both):

    name     
-------------
 USB-C Cable
(1 row)

💡 Hint: join products to order_items; keep the rows where the right side's key IS NULL.


Show the solution to Exercise 3
-- Exercise 3: Shelf warmers — products never ordered, both spellings
SELECT p.name
FROM products AS p
LEFT JOIN order_items AS oi ON oi.product_id = p.product_id
WHERE oi.product_id IS NULL;

SELECT p.name
FROM products AS p
WHERE NOT EXISTS (
  SELECT 1 FROM order_items AS oi WHERE oi.product_id = p.product_id
);

Exercise 4: The org chart line

What to do: Every employee with their title and their manager's name — including the one who has no manager.

Sample output:

 employee |   title    | manager 
----------+------------+---------
 Nina     | CEO        | 
 Omar     | CTO        | Nina
 Priya    | Sales Head | Nina
 Arjun    | Engineer   | Omar
 Lena     | Engineer   | Omar
 Dev      | Sales Rep  | Priya
(6 rows)

💡 Hint: self join under two aliases; LEFT so the CEO survives.


Show the solution to Exercise 4
-- Exercise 4: The org chart line
SELECT e.name AS employee, e.title, m.name AS manager
FROM employees AS e
LEFT JOIN employees AS m ON m.employee_id = e.manager_id
ORDER BY e.employee_id;

Exercise 5: Revenue per supplier

What to do: Delivered revenue per supplier, biggest first. One delivered product has no supplier — its revenue must still show (as a nameless row), not disappear.

Sample output:

   supplier   | revenue 
--------------+---------
 TechSource   | 3598.00
 PageTurners  |  340.00
 HomeGoods Co |   80.00
              |   45.00
(4 rows)

💡 Hint: join order_items to orders (for the status) and on to products, then LEFT JOIN suppliers; ORDER BY revenue DESC NULLS LAST.


Show the solution to Exercise 5
-- Exercise 5: Revenue per supplier
-- LEFT JOIN suppliers: the Desk Lamp has no supplier, and its revenue
-- should still appear (as the NULL row) rather than silently vanish.
SELECT s.name AS supplier,
       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
LEFT JOIN suppliers AS s ON s.supplier_id = p.supplier_id
WHERE o.status = 'delivered'
GROUP BY s.name
ORDER BY revenue DESC NULLS LAST;

Exercise 6: Delivered counts, nobody dropped

What to do: Every customer with their number of delivered orders — all six customers present, zeroes included. (This is the ON-vs-WHERE lesson as a question.)

Sample output:

 first_name | delivered_orders 
------------+------------------
 Asha       |                2
 Ravi       |                2
 Meera      |                1
 Sara       |                1
 John       |                0
 Vikram     |                0
(6 rows)

💡 Hint: the status = 'delivered' test goes in the ON, not the WHERE.


Show the solution to Exercise 6
-- Exercise 6: Delivered-order counts, nobody dropped
-- The status test lives in ON: it decides what MATCHES, not who is kept.
SELECT c.first_name, count(o.order_id) AS delivered_orders
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.customer_id
                     AND o.status = 'delivered'
GROUP BY c.customer_id, c.first_name
ORDER BY delivered_orders DESC, c.first_name;

Exercise 7: The fan-out audit

What to do: In one query over orders JOIN order_items, show the joined row count and the true number of orders, side by side.

Sample output:

 joined_rows | actual_orders 
-------------+---------------
          13 |             9
(1 row)

💡 Hint: count(*) vs count(DISTINCT o.order_id) — the gap is the fan-out.


Show the solution to Exercise 7
-- Exercise 7: The fan-out audit
SELECT count(*)                   AS joined_rows,
       count(DISTINCT o.order_id) AS actual_orders
FROM orders AS o
JOIN order_items AS oi ON oi.order_id = o.order_id;

Exercise 8: Who do we actually know?

What to do: Which customers have at least one event in the events table? Each name once, however many events they have.

Sample output:

 first_name 
------------
 Asha
 Ravi
 Vikram
(3 rows)

💡 Hint: a semi-join — WHERE EXISTS (SELECT 1 FROM events e WHERE ...). Note Vikram: he browses but has never ordered.

Show the solution to Exercise 8
-- Exercise 8: Who do we actually know?
-- A semi-join: EXISTS never duplicates a customer, however many events.
SELECT c.first_name
FROM customers AS c
WHERE EXISTS (SELECT 1 FROM events AS e WHERE e.customer_id = c.customer_id)
ORDER BY c.customer_id;

Common mistakes

Mistake What happens Fix
Filtering a LEFT JOIN's right table in WHERE Silently becomes an INNER JOIN Move the condition into ON
Counting after a fan-out join Inflated totals count(DISTINCT key), or aggregate before joining
Missing/wrong ON condition Accidental CROSS JOIN, huge result Join on the foreign key = primary key pair
NATURAL JOIN Join condition changes when columns are added Explicit ON or USING
INNER self join through a nullable key The root row (CEO) vanishes LEFT JOIN
Unaliased columns in multi-table queries Ambiguity errors, unreadable code Alias every table, prefix every column

Quick recap

  • Joins stitch tables where foreign key = primary key; INNER keeps matches only.
  • LEFT keeps every left row, padding misses with NULL — and IS NULL on the right key is the anti-join.
  • FULL OUTER compares sets; CROSS multiplies them (occasionally on purpose).
  • Self joins are one table under two aliases; keep nullable roots with LEFT.
  • Chain joins from the fact table outward; WHERE/GROUP BY work unchanged.
  • Fan-out multiplies rows, so always know your grain; in an outer join, conditions on the kept side go in WHERE and conditions on the optional side go in ON.
  • USING tidies identical key names, NATURAL JOIN is never worth the risk, and EXISTS/NOT EXISTS answer "has one" and "has none".

Checklist

Before Part 6, make sure you can:

  • Predict the row count of an INNER vs LEFT join on shopdb's customers/orders.
  • Write the anti-join ("never ordered") both ways.
  • Join four tables to compute revenue per category, delivered only.
  • Explain why WHERE right.col = x breaks a LEFT JOIN, and fix it.
  • Spot a fan-out and correct a count with DISTINCT.

Read more: the official joins tutorial and the joined-tables section of the queries chapter.

Search the guide