Joining Tables · Lesson 29 of 64

SQL Joining Several Tables

What you will learn

  • How to chain several joins in one query
  • How to build a long join one step at a time
  • How to mix inner and left joins
  • How to keep an eye on the row count

This lesson runs on the sample database you chose in lesson 1.1 (use the Example data picker at the top). Edit any query and press Run. Reset data puts the original rows back.

1. Follow the keys

Real questions often need data from several tables: "which customer bought which product?" crosses customers, orders, order lines and products. Draw the path of foreign keys from the table you start with to the one you want, and add one join for each step.

customers -- orders -- order_items -- products
branches -- accounts -- transactions        (and customers -- accounts)
students -- enrollments -- sections -- courses

Each double dash is a foreign key (lesson 4.1). A join per link means three joins for four tables.

2. Add one join at a time

Start with two tables and check the result. Add the third and check again. A long join written in one go is hard to debug:

Step 1: orders with their customer.

SELECT o.order_id, c.last_name
FROM orders AS o
JOIN customers AS c ON c.customer_id = o.customer_id
ORDER BY o.order_id LIMIT 3;
order_id  last_name
--------  ---------
       1  Wang
       2  Das
       3  Bianchi
(3 rows)

Step 2: add the order lines.

SELECT o.order_id, c.last_name, i.line_no, i.product_id, i.quantity
FROM orders AS o
JOIN customers AS c ON c.customer_id = o.customer_id
JOIN order_items AS i ON i.order_id = o.order_id
ORDER BY o.order_id, i.line_no LIMIT 4;
order_id  last_name  line_no  product_id  quantity
--------  ---------  -------  ----------  --------
       1  Wang             1          13         1
       1  Wang             2          27         1
       1  Wang             3          26         1
       1  Wang             4          30         1
(4 rows)

Step 3: add the product names.

SELECT o.order_id, c.last_name, p.name AS product, i.quantity, i.unit_price
FROM orders AS o
JOIN customers AS c ON c.customer_id = o.customer_id
JOIN order_items AS i ON i.order_id = o.order_id
JOIN products AS p ON p.product_id = i.product_id
ORDER BY o.order_id, i.line_no LIMIT 4;
order_id  last_name  product         quantity  unit_price
--------  ---------  --------------  --------  ----------
       1  Wang       Pruning shears         1        29.5
       1  Wang       Camping mug            1        21.6
       1  Wang       Storage box            1        24.0
       1  Wang       Rain poncho            1       32.45
(4 rows)

Step 1: transactions with their account.

SELECT t.txn_id, t.kind, a.account_type
FROM transactions AS t
JOIN accounts AS a ON a.account_id = t.account_id
ORDER BY t.txn_id LIMIT 3;
txn_id  kind     account_type
------  -------  ------------
     1  deposit  checking
     2  deposit  savings
     3  deposit  checking
(3 rows)

Step 2: add the owner.

SELECT t.txn_id, t.kind, a.account_type, c.full_name
FROM transactions AS t
JOIN accounts AS a ON a.account_id = t.account_id
JOIN customers AS c ON c.customer_id = a.customer_id
ORDER BY t.txn_id LIMIT 4;
txn_id  kind        account_type  full_name
------  ----------  ------------  ------------
     1  deposit     checking      Diego Zhang
     2  deposit     savings       Ibrahim Abdi
     3  deposit     checking      Paulo Meyer
     4  withdrawal  checking      Diego Zhang
(4 rows)

Step 3: add the branch of the account.

SELECT t.txn_id, t.kind, t.amount_cents, c.full_name, b.name AS branch
FROM transactions AS t
JOIN accounts AS a ON a.account_id = t.account_id
JOIN customers AS c ON c.customer_id = a.customer_id
JOIN branches AS b ON b.branch_id = a.branch_id
ORDER BY t.txn_id LIMIT 4;
txn_id  kind        amount_cents  full_name     branch
------  ----------  ------------  ------------  ----------
     1  deposit            54800  Diego Zhang   University
     2  deposit            53200  Ibrahim Abdi  University
     3  deposit            76000  Paulo Meyer   Central
     4  withdrawal         23900  Diego Zhang   University
(4 rows)

Step 1: enrollments with their student.

SELECT e.student_id, e.section_id, s.last_name
FROM enrollments AS e
JOIN students AS s ON s.student_id = e.student_id
ORDER BY e.student_id, e.section_id LIMIT 3;
student_id  section_id  last_name
----------  ----------  ---------
         1          19  Khan
         1          30  Khan
         1          41  Khan
(3 rows)

Step 2: add the section.

SELECT e.student_id, s.last_name, e.section_id, sec.term, sec.course_id
FROM enrollments AS e
JOIN students AS s ON s.student_id = e.student_id
JOIN sections AS sec ON sec.section_id = e.section_id
ORDER BY e.student_id, e.section_id LIMIT 4;
student_id  last_name  section_id  term         course_id
----------  ---------  ----------  -----------  ---------
         1  Khan               19  2026-Spring          9
         1  Khan               30  2025-Spring         14
         1  Khan               41  2025-Spring         19
         2  Haque               4  2026-Spring          2
(4 rows)

Step 3: add the course title.

SELECT s.last_name, c.code, c.title, sec.term, e.grade
FROM enrollments AS e
JOIN students AS s ON s.student_id = e.student_id
JOIN sections AS sec ON sec.section_id = e.section_id
JOIN courses AS c ON c.course_id = sec.course_id
ORDER BY e.student_id, e.section_id LIMIT 4;
last_name  code     title           term         grade
---------  -------  --------------  -----------  -----
Khan       LANG102  Reading Circle  2026-Spring   NULL
Khan       ART101   Drawing         2025-Spring   49.2
Khan       CS301    Databases       2025-Spring   60.8
Haque      MATH201  Geometry        2026-Spring   NULL
(4 rows)

Each step adds columns, and (as long as each join follows a foreign key from child to parent) no new rows.

3. The row count should not change

When every added join goes from a child to its parent, the number of rows stays the same as the first table. When a join goes from a parent to its children, the rows multiply (one row per child). Compare:

SELECT (SELECT COUNT(*) FROM order_items) AS order_lines,
       (SELECT COUNT(*) FROM order_items AS i
          JOIN orders AS o ON o.order_id = i.order_id
          JOIN customers AS c ON c.customer_id = o.customer_id
          JOIN products AS p ON p.product_id = i.product_id) AS after_three_joins_to_parents;
order_lines  after_three_joins_to_parents
-----------  ----------------------------
       5790                          5790
(1 row)
SELECT (SELECT COUNT(*) FROM transactions) AS ledger_rows,
       (SELECT COUNT(*) FROM transactions AS t
          JOIN accounts AS a ON a.account_id = t.account_id
          JOIN customers AS c ON c.customer_id = a.customer_id
          JOIN branches AS b ON b.branch_id = a.branch_id) AS after_three_joins_to_parents;
ledger_rows  after_three_joins_to_parents
-----------  ----------------------------
       7415                          7415
(1 row)
SELECT (SELECT COUNT(*) FROM enrollments) AS enrollments,
       (SELECT COUNT(*) FROM enrollments AS e
          JOIN students AS s ON s.student_id = e.student_id
          JOIN sections AS sec ON sec.section_id = e.section_id
          JOIN courses AS c ON c.course_id = sec.course_id) AS after_three_joins_to_parents;
enrollments  after_three_joins_to_parents
-----------  ----------------------------
       1002                          1002
(1 row)

The numbers match: each extra join only added columns. This check is cheap and catches a wrong ON immediately.

4. Mixing inner and left joins

Use LEFT JOIN for the links that may be missing, and JOIN for those that always exist. Start from the table whose rows you want complete:

Every order with its employee's name, where the order has an employee (321 online orders have none):

SELECT o.order_id, o.status, e.name AS employee
FROM orders AS o
LEFT JOIN employees AS e ON e.employee_id = o.employee_id
ORDER BY o.order_id LIMIT 6;
order_id  status     employee
--------  ---------  -----------
       1  delivered  Mina Kamau
       2  delivered  Mei Costa
       3  delivered  Mina Kamau
       4  paid       Ugo Jensen
       5  delivered  Arjun Cohen
       6  delivered  Yusuf Kumar
(6 rows)

Every account with its cards, if any (many accounts have no card):

SELECT a.account_id, a.account_type, k.last4, k.status
FROM accounts AS a
LEFT JOIN cards AS k ON k.account_id = a.account_id
ORDER BY a.account_id, k.card_id LIMIT 6;
account_id  account_type  last4  status
----------  ------------  -----  -------
         1  checking      2663   active
         2  savings       NULL   NULL
         3  savings       NULL   NULL
         4  checking      4347   expired
         5  checking      5104   expired
         6  checking      3842   active
(6 rows)

Every section with its enrolled students' count and teacher, keeping sections even if nobody is enrolled:

SELECT sec.section_id, t.name AS teacher, COUNT(e.student_id) AS students
FROM sections AS sec
JOIN teachers AS t ON t.teacher_id = sec.teacher_id
LEFT JOIN enrollments AS e ON e.section_id = sec.section_id
GROUP BY sec.section_id, t.name
ORDER BY sec.section_id LIMIT 6;
section_id  teacher        students
----------  -------------  --------
         1  Liam Patel           15
         2  Bruno Bianchi        20
         3  Sven Silva           15
         4  Kira Perez           25
         5  Nico Diaz            32
         6  Sven Silva           19
(6 rows)

5. Aggregating over a long join

A long join plus GROUP BY answers questions that cross many tables:

Revenue per product category (order lines, products and categories):

SELECT cat.name AS category, ROUND(SUM(i.quantity * i.unit_price), 2) AS revenue
FROM order_items AS i
JOIN products AS p ON p.product_id = i.product_id
JOIN categories AS cat ON cat.category_id = p.category_id
GROUP BY cat.name ORDER BY revenue DESC, category LIMIT 5;
category     revenue
----------  --------
Kitchen     44832.29
Garden      43035.76
Stationery  41386.72
Outdoor     40286.54
Fitness     33964.01
(5 rows)

Total deposited per branch (ledger, account, branch):

SELECT b.name AS branch, SUM(t.amount_cents) AS deposited_cents
FROM transactions AS t
JOIN accounts AS a ON a.account_id = t.account_id
JOIN branches AS b ON b.branch_id = a.branch_id
WHERE t.kind = 'deposit'
GROUP BY b.name ORDER BY deposited_cents DESC, branch;
branch      deposited_cents
----------  ---------------
Central            19288700
University         18033200
Airport            16668100
Old Town           16575900
Riverside          16126900
Harbour            12749000
(6 rows)

Average grade per course (enrollments, sections, courses):

SELECT c.code, c.title, COUNT(e.grade) AS graded, ROUND(AVG(e.grade), 1) AS average_grade
FROM enrollments AS e
JOIN sections AS sec ON sec.section_id = e.section_id
JOIN courses AS c ON c.course_id = sec.course_id
GROUP BY c.course_id, c.code, c.title
ORDER BY average_grade DESC, c.course_id LIMIT 5;
code    title      graded  average_grade
------  ---------  ------  -------------
ART101  Drawing        40           76.3
HUM201  Geography      25           73.2
HUM301  Civics         36           73.1
ART202  Drama          59           72.8
SCI201  Chemistry      49           72.0
(5 rows)

Worked example: plan a four-table join

"Show the name of every student with the title of each course they take."

Step Do
1 list the tables: students, enrollments, sections, courses
2 draw the keys: students.student_id = enrollments.student_id; enrollments.section_id = sections.section_id; sections.course_id = courses.course_id
3 start from enrollments, the table with one row per fact
4 add the three joins one at a time, checking the row count
5 choose the columns and sort

The row count equals the number of enrollments at every step, because every join goes from a child to its parent. The tables are from the School sample.

Common mistakes

  • Writing the whole join at once and then not knowing which ON is wrong.
  • A missing ON condition, which multiplies the rows.
  • Joining on the wrong key (an id from another table that happens to be a number).
  • An inner join on an optional link, which silently drops rows.
  • Not checking the row count.

Key takeaways

  • One join for each foreign key link; add them one at a time.
  • Joining child to parent adds columns, not rows; parent to child multiplies rows.
  • Use LEFT JOIN for links that may be missing.
  • Compare the row count before and after each join.

Practice

1. How many joins do you need to combine four tables in a chain?

Show answer

Three: one for each link.

2. Which table should you start from to list each order line with product and customer?

Show answer

order_items, the table with one row per line, joining up to orders, customers and products.

3. A three-table join suddenly returns many more rows than the first table. What is likely wrong?

Show answer

A join goes from a parent to its children (or its ON condition is wrong), so rows multiply.

4. When should a link in a chain be a LEFT JOIN?

Show answer

When the link may be missing and you do not want to lose the rows that lack it.

5. Why add the joins one at a time?

Show answer

You can check the result after each step, so a wrong condition is found at once.

6. What does the join of child to parent add to the result?

Show answer

Columns of the parent, but no extra rows.