Joining Many Tables

Updated · 10 min read
mediumPostgreSQL 18sqljoinsusingnatural-joinfan-outinterview

Real questions often need three, four or five tables, and you join them one at a time, each JOIN adding one table to the rows built so far. "Which courses is each student enrolled in, by name?" needs enrollments for the links, students for the names and courses for the titles. This lesson shows how to chain joins, the USING shorthand, two older styles to avoid (NATURAL JOIN and comma joins), and the most expensive mistake in reporting: a join that quietly duplicates rows, so every total comes out too big. It ends with the chapter's checkpoint, which uses everything from this chapter and the last.

In One Minute

  • Chain joins: FROM a JOIN b ON ... JOIN c ON ...; each join adds one table.
  • Start from the table whose rows you want, often the one in the middle, like enrollments.
  • JOIN b USING (student_id) is short for ON a.student_id = b.student_id when the column names match.
  • Avoid NATURAL JOIN (it guesses the columns) and comma joins in FROM (easy to leave a table unjoined).
  • Joining two independent child tables multiplies rows: check counts before trusting totals.

Three Tables, Step by Step

Each JOIN attaches one more table to the rows built so far. Every enrollment, with names instead of ids:

SQL▶ Try it
SELECT s.first_name, c.title, e.status
FROM enrollments AS e
JOIN students AS s ON s.student_id = e.student_id
JOIN courses  AS c ON c.course_id  = e.course_id
ORDER BY s.student_id, c.course_id;
Output
 first_name |       title       |  status
------------+-------------------+-----------
 Srihitha   | Java Basics       | completed
 Srihitha   | Java OOP          | completed
 Srihitha   | Java Collections  | active
 Srihitha   | SQL Basics        | active
 Advitha    | Java Basics       | active
 Advitha    | SQL Basics        | active
 Navika     | JavaScript Basics | active
(7 rows)

Read it in order. FROM enrollments gives seven rows. The first JOIN adds each enrollment's student; each enrollment has exactly one, so there are still seven rows. The second adds each enrollment's course, again one each. The result has one row per enrollment, with names from two other tables.

Starting from enrollments, the table in the middle that links the other two, keeps this simple. Every row of the result is one enrollment, and each join only adds detail.

enrollments in the middle; each JOIN attaches one student and one course to each of the seven rows

More Tables, Same Pattern

You can keep adding joins, including joins on two columns. Active enrollments with each student's time zone, from cities, which is keyed on (city, state):

SQL▶ Try it
SELECT s.first_name, ci.time_zone, c.title
FROM enrollments AS e
JOIN students AS s  ON s.student_id = e.student_id
JOIN cities   AS ci ON ci.city = s.city AND ci.state = s.state
JOIN courses  AS c  ON c.course_id = e.course_id
WHERE e.status = 'active'
ORDER BY s.student_id, c.course_id;
Output
 first_name |      time_zone      |       title
------------+---------------------+-------------------
 Srihitha   | America/Los_Angeles | Java Collections
 Srihitha   | America/Los_Angeles | SQL Basics
 Advitha    | America/Los_Angeles | Java Basics
 Advitha    | America/Los_Angeles | SQL Basics
 Navika     | America/Chicago     | JavaScript Basics
(5 rows)

The cities join hangs off students, not enrollments: an ON can refer to any table joined before it. Mixing inner and left joins works the same way, and the order matters only for outer joins: a LEFT JOIN keeps the rows built up to that point.

USING: A Shorter ON

When both tables name the join column the same, USING (column) replaces the ON condition:

SQL▶ Try it
SELECT s.first_name, c.title
FROM enrollments AS e
JOIN students AS s USING (student_id)
JOIN courses  AS c USING (course_id)
ORDER BY s.first_name, c.title;
Output
 first_name |       title
------------+-------------------
 Advitha    | Java Basics
 Advitha    | SQL Basics
 Navika     | JavaScript Basics
 Srihitha   | Java Basics
 Srihitha   | Java Collections
 Srihitha   | Java OOP
 Srihitha   | SQL Basics
(7 rows)

Same seven rows. USING (student_id) means ON e.student_id = s.student_id, and the result has a single student_id column instead of two, so a bare student_id in the SELECT list isn't ambiguous. It only works when the names match exactly; for mentor_id to student_id, you need ON.

Two Styles to Avoid

NATURAL JOIN joins on every column the two tables happen to share by name. That sounds convenient until someone adds a column. Here's a natural join that works, and then the same join after both tables get a notes column:

SQL▶ Try it
ALTER TABLE students ADD COLUMN notes TEXT;
ALTER TABLE enrollments ADD COLUMN notes TEXT;
 
SELECT count(*) AS rows
FROM students NATURAL JOIN enrollments;
Output
ALTER TABLE
 
ALTER TABLE
 
 rows
------
    0
(1 row)

Zero rows. Before the change it returned seven; now it also requires students.notes = enrollments.notes, and NULL = NULL is never true. Nobody touched the query, and it broke anyway. Write the columns in ON or USING so the join says exactly what it matches.

Adding a column with the same name to both tables silently changes what NATURAL JOIN matches: 7 rows become 0

Comma joins list tables in FROM and put the join conditions in WHERE:

SQL
SELECT s.first_name, c.title, e.status
FROM students AS s, enrollments AS e, courses AS c
WHERE e.student_id = s.student_id
  AND c.course_id  = e.course_id
  AND e.status = 'completed';

It works, and you'll see it in older code, but join conditions and filters are mixed together, and forgetting one condition gives an accidental cross join, as CROSS JOIN showed. Explicit JOIN ... ON keeps each table next to its condition.

Checking a Join Didn't Duplicate Rows

Joining one parent to two independent child tables pairs every row of one child with every row of the other. This query tries to total each student's payments, but also joins their enrollments:

SQL▶ Try it
SELECT s.first_name, count(*) AS rows, sum(p.amount_usd) AS total
FROM students AS s
JOIN enrollments AS e ON e.student_id = s.student_id
JOIN payments    AS p ON p.student_id = s.student_id
GROUP BY s.student_id, s.first_name
ORDER BY s.student_id;
Output
 first_name | rows |  total
------------+------+---------
 Srihitha   |   20 | 6800.00
 Navika     |    2 |  450.00
(2 rows)

Srihitha appears to have paid $6,800.00. She paid $1,700.00. Her four enrollments and five payments were paired with each other, 4 × 5 = 20 rows, so every payment was counted four times. This is called fan-out, and the query gives no warning. Without the unneeded join, the total is right:

SQL▶ Try it
SELECT s.first_name, count(*) AS rows, sum(p.amount_usd) AS total
FROM students AS s
JOIN payments AS p ON p.student_id = s.student_id
GROUP BY s.student_id, s.first_name
ORDER BY s.student_id;
Output
 first_name | rows |  total
------------+------+---------
 Srihitha   |    5 | 1700.00
 Navika     |    2 |  450.00
(2 rows)
Srihitha's 4 enrollments times 5 payments make 20 rows, so her 1,700.00 is summed as 6,800.00

A quick check catches it: count the rows before and after each join. If a join you expected to add detail made the row count jump, find out why before trusting any total. Subqueries shows how to summarize each child separately when you need both.

Common Mistakes

Joining tables you don't need. Extra joins can multiply rows. Join only what the result uses.

Summing across two child tables. Fan-out inflates totals. Summarize each separately.

NATURAL JOIN. It matches every shared column name, including ones added later. Name the columns.

Forgetting a condition in a comma join. Every table must be connected, or you get a cross join.

Interview Corner

How do you join three tables?

Chain the joins: FROM a JOIN b ON ... JOIN c ON .... Each join adds one table to the rows built so far, and its ON condition can refer to any table already joined.

Why is NATURAL JOIN considered risky?

It joins on every column with the same name in both tables. Adding a column with a shared name, such as notes or updated_at, silently changes the join, often to zero rows.

Why might a SUM be too large after a join?

Fan-out: joining a row to several rows in one table and several in another repeats each row once per combination, so values are summed multiple times.

Practice

Challenge (chapter checkpoint): For students in California, list each course they're enrolled in with the total they've paid for it, showing $0.00 for courses not paid for yet, and keep only courses where the total paid is under the course fee. Show the student's first name, the course title, the fee and the amount paid, sorted by student and course.

Show solution
SQL▶ Try it
SELECT s.first_name, c.title, c.fee_usd,
       coalesce(sum(p.amount_usd), 0.00) AS paid
FROM students AS s
JOIN enrollments AS e ON e.student_id = s.student_id
JOIN courses     AS c ON c.course_id  = e.course_id
LEFT JOIN payments AS p
  ON p.student_id = e.student_id
 AND p.course_id  = e.course_id
WHERE s.state = 'CA'
GROUP BY s.student_id, s.first_name, c.course_id, c.title, c.fee_usd
HAVING coalesce(sum(p.amount_usd), 0.00) < c.fee_usd
ORDER BY s.student_id, c.course_id;
Output
 first_name |    title    | fee_usd |  paid
------------+-------------+---------+--------
 Srihitha   | SQL Basics  |  400.00 | 200.00
 Advitha    | Java Basics |  450.00 |   0.00
 Advitha    | SQL Basics  |  400.00 |   0.00
(3 rows)

WHERE keeps California students; inner joins add their enrollments and courses; the LEFT JOIN on both key columns adds payments without dropping unpaid enrollments; coalesce turns "no payments" into 0.00; and HAVING keeps courses still owed. Srihitha owes on SQL Basics, and Advitha hasn't paid for either of her courses. Payments are the only child table summed, so there's no fan-out.

Quick check: Joining many tables

3 questions
1FROM enrollments e JOIN students s ON ... JOIN courses c ON ...: how many rows, if every enrollment has one student and one course?
2What does JOIN students USING (student_id) mean?
3Srihitha has 4 enrollments and 5 payments. Joining both to students and summing payments gives what?

Key Takeaways

You want toWrite
Three tablesFROM enrollments e JOIN students s ON s.student_id = e.student_id JOIN courses c ON c.course_id = e.course_id
Same, shorter... JOIN students s USING (student_id) JOIN courses c USING (course_id)
Avoid fan-outSum one child table per query, or summarize each in a subquery

Was this tutorial helpful?

Lesson 42 of 115