…
…
SQL and Database Fundamentals · Lesson 17 / 41 · Joins
PreviewIn this lesson you will
You can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
Student 17, Lena Nakamura, asked for her transcript: which course she took in which term, the course name, and her grades. This information is spread across four tables, and the JOINs you have written so far connected only two tables. Also, for registration week the course catalog must show the name of the prerequisite course next to each course, and the prerequisite sits in another row of the same course table.
Lena's transcript will look like this. Each row is one enrollment, with the term name, course code, course name, and grades side by side:
| term | code | course | midterm | final_exam | letter_grade |
|---|---|---|---|---|---|
| 2025-Fall | BUS101 | Introduction to Business | 83 | 85 | B+ |
| 2025-Fall | BUS301 | Entrepreneurship | 76 | 84 | B+ |
| 2025-Fall | GEN101 | Academic Writing | 90 | 75 | B+ |
| 2026-Spring | BUS102 | Accounting I | 86 | 78 | B+ |
| 2026-Spring | BUS204 | Principles of Marketing | 74 | 76 | B |
| 2026-Spring | GEN102 | Quantitative Reasoning I | 72 | 100 | A- |
| 2026-Spring | GEN104 | Information Technology Skills | 93 |
The columns of these ten rows come from four different tables. The grades (midterm, final_exam, letter_grade) are in enrollment. The course code and name are in course. The term name is in term. There is no direct link between an enrollment and a course or a term; the bridge is course_offering, the table of course sections. In lesson 15 you joined two tables with JOIN ... ON, and in lesson 16 you kept unmatched rows with LEFT JOIN. In this lesson you will use the same tools one after another.
In this lesson you will:
LEFT JOIN in a chain.In lesson 14 you learned to draw a path in the schema to answer a question: find the table that holds the answer, then follow the arrows to it from the table you start with. The path for "the course name of an enrollment" was enrollment → course_offering → course. In that lesson you walked this path with separate queries and carried the ids by hand. Now we turn each arrow of the path into a JOIN line.
The rule is simple: every arrow on the path is a foreign key and becomes one JOIN ... ON line. The first table goes in FROM. Every next table is added with its own JOIN line, and its ON condition connects it to a table that was already added. In the schema below, the path of the transcript is drawn with orange arrows, and the tables that are not on the path are faded.
The three orange arrows in the schema mean three JOIN lines. There is no direct arrow from enrollment to course, which is the dashed line: an enrollment holds the number of the section, not the number of the course. That is why course_offering cannot be skipped.
Let's start with a small chain: the course names and letter grades of student 1. The path is enrollment → course_offering → course; the term is not needed for this question. Put the lines in the right order.
Put the lines of the query that returns the course names and letter grades of student 1 in order.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
This query returns 6 rows: Introduction to Industrial Engineering, Operations Research I and II, Probability and Statistics, Academic Writing, and Information Technology Skills. Let's correct a common misunderstanding here: "every JOIN must connect to the first table in FROM." The truth is that the new table connects to any table already added to the chain. The course table cannot connect to enrollment, because the two have no shared column; but it can connect to course_offering, because course_id is there. The arrow in the schema decides which table to connect to.
It is tempting to write a four-table query in one go and run it. But if the result is wrong, it is hard to find which line broke it. The safe way is to add the chain one link at a time and look at the row count after each link. We do this with COUNT(*).
Example 1 (case): Count the chain link by link
-- 1. Enrollments only SELECT COUNT(*) FROM enrollment e; -- 2. Section added SELECT COUNT(*) FROM enrollment e JOIN course_offering o ON o.id = e.offering_id; -- 3. Course added SELECT COUNT(*) FROM enrollment e JOIN course_offering o ON o.id = e.offering_id JOIN course c ON c.id = o.course_id; -- 4. Term added SELECT COUNT(*) FROM enrollment e JOIN course_offering o ON o.id = e.offering_id JOIN course c ON c.id = o.course_id JOIN term t ON t.id = o.term_id;
Result (four queries, in order):
| Step | Table added | COUNT(*) |
|---|---|---|
| 1 | enrollment | 781 |
| 2 | course_offering | 781 |
| 3 | course | 781 |
| 4 | term | 781 |
All four steps give 781. This is not a coincidence. At every step we went from a table on the "many" side to a table on the "one" side: every enrollment has exactly one section, and every section has exactly one course and exactly one term. The foreign key columns (offering_id, course_id, term_id) cannot be empty, and each one points to an existing row. In this case every row finds exactly one match on the other side; no row is dropped and no row is repeated. The rule is: an INNER JOIN from the many side to the one side does not change the row count when the foreign key is filled.
This is the opposite of the misunderstanding "every new JOIN increases the row count." Adding a JOIN does not add rows; it only adds columns to the chain. If the count changes, there is a reason, and you need to know that reason: if it dropped, an INNER JOIN removed rows without a match (lesson 15); if it grew, you moved from the "one" side to the "many" side. You will see the second case in detail in the next lesson.
The cell below counts only the enrollment table, and three JOIN lines wait as comments. Run it first. Then remove the -- at the start of the first JOIN line and run again; open the other two lines in order. Look at the number at every step. Then try one experiment: leave only the third line (course) open and comment out the second again. What happened?
Try it now· not graded; doesn't affect progress
In the last experiment PostgreSQL gives the error missing FROM-clause entry for table "o". It says: "there is no table defined as o in the query." The course line refers to o.course_id, but you closed the line that adds the table with the alias o. When you see this message, first check whether the JOIN line that defines that alias is missing or written later.
Now that the counts match, we can write the columns we want instead of COUNT(*). Two of the four tables have a name column, so we write every column with its prefix and give one of the two name columns an alias. Choose short aliases that fit the role: e for enrollment, o for offering, c for course, t for term.
Example 2 (case): The transcript of student 17
SELECT t.name AS term, c.code, c.name AS course, e.midterm, e.final_exam, e.letter_grade FROM enrollment e JOIN course_offering o ON o.id = e.offering_id JOIN course c ON c.id = o.course_id JOIN term t ON t.id = o.term_id WHERE e.student_id = 17 ORDER BY t.start_date, c.code;
| term | code | course | midterm | final_exam | letter_grade |
|---|---|---|---|---|---|
| 2025-Fall | BUS101 | Introduction to Business | 83 | 85 | B+ |
| 2025-Fall | BUS301 | Entrepreneurship | 76 | 84 | B+ |
| 2025-Fall | GEN101 | Academic Writing | 90 | 75 | B+ |
| 2026-Spring | BUS102 | Accounting I | 86 | 78 | B+ |
| 2026-Spring | BUS204 | Principles of Marketing | 74 | 76 | B |
| 2026-Spring |
(10 rows)
Notice how the query is read: WHERE filters by student_id in the enrollment table, while ORDER BY uses the start_date of the term table. Once the chain is built, all columns of the four tables are in the same row, and you can filter and sort by any of them. We sorted the terms by start date, not by name. If you sorted by name, "2026-Fall" would come before "2026-Spring" in alphabetical order, which is the wrong order in time; the date always gives the right order. Entrepreneurship appears twice: Lena passed it in 2025-Fall with a B+ and took it again in 2026-Fall to raise her grade. These are two separate enrollments in two separate sections; a repeated row here is not an error.
Now think of someone who tries to skip the table in the middle. enrollment has offering_id and course has id; both are numbers. Why not connect them directly?
What happens if the course line in the transcript query is written as JOIN course c ON c.id = e.offering_id?
SELECT t.name AS term, c.code, c.name AS course, e.letter_grade FROM enrollment e JOIN course_offering o ON o.id = e.offering_id JOIN course c ON c.id = e.offering_id JOIN term t ON t.id = o.term_id WHERE e.student_id = 17;
This mistake is a relative of the "two bare ids" trap in lesson 15. The rule is the same: the foreign key on one side of the ON condition must match the primary key of the table it points to. The name offering_id already tells you: this column points to the course_offering table, not to the course table.
In lesson 16 you saw that LEFT JOIN keeps the unmatched rows of the left table and leaves the columns of the other table NULL. There is a subtlety to this in a chain. Department heads want the list of all instructors: next to each instructor, the codes of the courses they teach, and an instructor who teaches nothing must still appear.
The path is instructor → course_offering → course. To keep an instructor with no sections, the first JOIN must be LEFT. What about the second?
Example 3 (case): All instructors and the courses they teach
SELECT i.title, i.last_name, c.code FROM instructor i LEFT JOIN course_offering o ON o.instructor_id = i.id LEFT JOIN course c ON c.id = o.course_id ORDER BY i.last_name, c.code;
Result (55 rows; rows 9 to 11 shown):
| title | last_name | code |
|---|---|---|
| Lecturer | Cohen | GEN101 |
| Assistant Professor | Cohen | NULL |
| Associate Professor | Costa | CPR104 |
(55 rows)
The second row, Assistant Professor Yuki Cohen (instructor 18), has not offered any section in these terms. The first LEFT JOIN kept her row and left all columns of o NULL. In the second JOIN the condition is c.id = o.course_id, and in this row o.course_id is NULL. NULL is not equal to anything, so Cohen matches no course. Because the second JOIN is also LEFT, the row is kept again and c.code shows as NULL. 54 section rows plus 1 instructor with no courses: 55.
Now make the second JOIN an INNER join. The query is ready in the cell below. First run it as it is and find the second row. Then change the second LEFT JOIN to just JOIN and run again: how far did the row count drop, and who disappeared?
Try it now· not graded; doesn't affect progress
The result drops to 54 rows and Yuki Cohen disappears from the list. The first LEFT JOIN had protected her, but the INNER JOIN after it applies the rule "drop rows without a match" to all joined rows. Her row finds no match in course, so it is dropped, and the work of the first JOIN is wasted. This is why "an INNER JOIN after a LEFT JOIN is harmless" is wrong.
The second request of the case is the course catalog: next to each course, the name of its prerequisite course. In lesson 14 you saw that an arrow from the course table points back to course: prerequisite_id holds the id of another course in the same table. For example, the prerequisite_id of Algorithms and Programming II is 1; this points to course 1, Algorithms and Programming I.
To bring the name of the prerequisite, we join the course table to itself as if it were a second table. This is called a self join. There is no new word in the syntax; the same table appears twice, in FROM and in JOIN, each time with a different alias. Aliases are not optional here, they are required: if you wrote course.id, it would be unclear which of the two copies you mean. Give the aliases roles: c is the course itself, p is its prerequisite.
Example 4 (case): Courses and their prerequisites
SELECT c.code, c.name, p.code AS prerequisite_code, p.name AS prerequisite FROM course c JOIN course p ON p.id = c.prerequisite_id ORDER BY c.code;
| code | name | prerequisite_code | prerequisite |
|---|---|---|---|
| BUS203 | Accounting II | BUS102 | Accounting I |
| CPR102 | Algorithms and Programming II | CPR101 | Algorithms and Programming I |
| CPR104 | Databases II | CPR103 | Databases I |
| GEN103 | Quantitative Reasoning II | GEN102 | Quantitative Reasoning I |
| IND202 | Operations Research II | IND201 | Operations Research I |
| MIS203 | Business Analytics | MIS202 | Database Management |
| PSY202 | Social Psychology | PSY101 | Introduction to Psychology |
| SWE102 |
(9 rows)
Read the condition aloud: "the number of the prerequisite (p) equals the prerequisite_id of the course (c)." This is the same pattern you know from lesson 15: a foreign key on one side (c.prerequisite_id) and the primary key it points to on the other (p.id). The only difference is that both sides are the same table. The result has 9 rows because only 9 of the 33 courses have a prerequisite; the INNER JOIN dropped the 24 courses whose prerequisite_id is NULL. The catalog must show every course. The solution from lesson 16 works here too: write LEFT JOIN, and courses without a prerequisite stay with NULL.
Try it now· not graded; doesn't affect progress
In the first eight rows, the prerequisite is empty next to BUS101, and BUS203 shows BUS102. If you delete the LIMIT 8 line, you see all 33 rows. You can write p.name instead of p.code to bring the name of the prerequisite.
The most common mistake in a self join is to reverse the direction of the condition. What changes if you write p.prerequisite_id = c.id instead of p.id = c.prerequisite_id?
If the condition is written as ON p.prerequisite_id = c.id, what appears in the p.code column?
SELECT c.code, p.code AS prerequisite FROM course c JOIN course p ON p.prerequisite_id = c.id;
In lesson 15 we said "the two sides of an equality can swap places," and this is still true: p.id = c.prerequisite_id and c.prerequisite_id = p.id are the same condition. The reversed-direction mistake does not swap the sides of the equality; it changes which alias carries which column. In a self join the two aliases have the same columns, so this slip is very easy, and the query gives no warning.
Once the chain is built, GROUP BY and HAVING from lessons 12 and 13 work as before. The registrar wants to check a suspicion: some sections may have more students enrolled than their capacity. To find this, we join sections with enrollments, count the enrollments of each section, and compare the count with the section's capacity. We also add two more tables to the chain so the report shows the course code and the term name.
Example 5 (case): Sections over capacity
SELECT o.id AS section, c.code, t.name AS term, o.capacity, COUNT(*) AS enrolled FROM course_offering o JOIN course c ON c.id = o.course_id JOIN term t ON t.id = o.term_id JOIN enrollment e ON e.offering_id = o.id GROUP BY o.id, c.code, t.name, o.capacity HAVING COUNT(*) > o.capacity ORDER BY o.id;
| section | code | term | capacity | enrolled |
|---|---|---|---|---|
| 47 | GEN101 | 2025-Fall | 50 | 77 |
| 48 | GEN101 | 2026-Fall | 40 | 79 |
| 49 | GEN102 | 2026-Spring | 30 | 41 |
(3 rows)
We built the group with the section number (o.id), not the course code: sections 47 and 48 are both GEN101. If we had grouped only by code, the enrollments of the two sections would be added into one row. To use o.capacity in HAVING, we also added it to GROUP BY; the code and term name we selected are there too. Here we put enrollment last and connected it to course_offering. This time we go from the "one" side (section) to the "many" side (enrollment); each section row repeats as many times as it has enrollments, and COUNT(*) counts exactly these repeats. A section with no enrollments would be dropped by the INNER JOIN, but a section over capacity always has enrollments, so this is not a problem in this question.
How should you read the result? The query gave no error and its logic is correct: three sections have more students enrolled than their capacity. The 2026-Fall section of Academic Writing has 79 students for 40 seats. This is not a query error; it is a problem in the data itself: the registration system did not check the capacity. The query answers "who, where, and by how much"; it does not answer "why" or "which students are the extra ones." Finding problems like this and reporting them to the registrar is at the center of the work expected from someone who works with databases.
A self join is not only for prerequisites. It appears whenever a row of a table points to another row in the same table, that is, whenever there is a hierarchy. An employee's manager is also an employee, and the parent of a category is also a category. In each case the table has a column that refers to the table itself.
Match each hierarchy example with the column that refers to the table itself.
For each row, pick its match from the list, then check.
employee table)category table)comment table)course table)Think of the employee table of a small company. It has five rows, and manager_id holds the id of each employee's manager. The general manager, Sofia, has no manager, so her manager_id is NULL.
employee
| id | name | manager_id |
|---|---|---|
| 1 | Sofia | NULL |
| 2 | Marcus | 1 |
| 3 | Elena | 1 |
| 4 | Kai | 2 |
| 5 | Dara | 2 |
Human resources wants a list of "each employee and the name of their manager." We give the aliases roles: e is the employee and m is the manager. The condition: "the number of the manager equals the employee's manager_id."
This query is written with an INNER JOIN. Who does not appear in the result?
SELECT e.name AS employee, m.name AS manager FROM employee e JOIN employee m ON m.id = e.manager_id;
Example 6 (outside the case): Employees and their managers
SELECT e.name AS employee, m.name AS manager FROM employee e LEFT JOIN employee m ON m.id = e.manager_id ORDER BY e.id;
| employee | manager |
|---|---|
| Sofia | NULL |
| Marcus | Sofia |
| Elena | Sofia |
| Kai | Marcus |
| Dara | Marcus |
(5 rows)
With LEFT JOIN, Sofia stays in the list and the manager column is empty. With an INNER JOIN you get 4 rows, and the general manager is not in the list. This is the same as the courses without a prerequisite in the catalog. One more point: Marcus appears in both roles, once in the employee column and twice in the manager column. This is why it helps to think of two copies of the same table: one row can be an employee in one copy and a manager in the other.
The students enrolled in the 2026-Fall section of Entrepreneurship (BUS301). This time the chain branches: from enrollment one arm goes to the student and one arm goes to the section; from the section, one goes to the course and one to the term. Every new table is still connected to a table that was already added.
SELECT s.student_no, s.first_name, s.last_name, e.midterm FROM enrollment e JOIN student s ON s.id = e.student_id JOIN course_offering o ON o.id = e.offering_id JOIN course c ON c.id = o.course_id JOIN term t ON t.id = o.term_id WHERE c.code = 'BUS301' AND t.name = '2026-Fall' ORDER BY s.last_name, s.first_name;
Result (first 5 of 16 rows):
| student_no | first_name | last_name | midterm |
|---|---|---|---|
| 202604001 | Felix | Abara | 62 |
A reversed direction in a self join. Someone who writes the course catalog builds the condition like this:
SELECT c.code, c.name, p.code AS prerequisite_code, p.name AS prerequisite FROM course c JOIN course p ON p.prerequisite_id = c.id ORDER BY c.code;
Result (first 3 of 9 rows):
| code | name | prerequisite_code | prerequisite |
|---|---|---|---|
| BUS102 | Accounting I | BUS203 | Accounting II |
| CPR101 | Algorithms and Programming I | CPR102 | Algorithms and Programming II |
| CPR103 | Databases I | CPR104 | Databases II |
The query gives no error and returns 9 rows, the same number as the correct query. But the prerequisite of Accounting I cannot be Accounting II; the table is turned around. The condition says "the prerequisite of p
JOIN ... ON line, every new table connects to a table already added, and a table in the middle cannot be skipped. Build the chain link by link and count with COUNT(*) after each link; a JOIN from the many side to the one side does not change the row count.LEFT JOIN disappear silently if the later JOINs are not LEFT too.c course, p prerequisite); the condition is built from the foreign key to the row it points to (p.id = c.prerequisite_id), and a reversed direction gives a wrong result without any error.Next lesson: In this lesson the row count stayed the same or dropped. In JOINs that go from the "one" side to the "many" side the count grows and totals get inflated; we will see how to catch this and fix it.
Exercises and quiz are for members
This lesson has 7 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
| A |
| 2026-Fall | BUS203 | Accounting II | 82 | NULL | NULL |
| 2026-Fall | BUS301 | Entrepreneurship | 94 | NULL | NULL |
| 2026-Fall | GEN103 | Quantitative Reasoning II | 100 | NULL | NULL |
| GEN102 |
| Quantitative Reasoning I |
| 72 |
| 100 |
| A- |
| 2026-Spring | GEN104 | Information Technology Skills | 93 | 96 | A |
| 2026-Fall | BUS203 | Accounting II | 82 | NULL | NULL |
| 2026-Fall | BUS301 | Entrepreneurship | 94 | NULL | NULL |
| 2026-Fall | GEN103 | Quantitative Reasoning II | 100 | NULL | NULL |
| SWE101 |
| Introduction to Programming |
| SWE201 | Data Structures | SWE102 | Object-Oriented Programming |
| 202404002 |
| Noah |
| Abara |
| 61 |
| 202604003 | Ali | Ahmed | 64 |
| 202604002 | Zara | Cohen | 90 |
| 202504005 | Hiro | Fernández | 90 |
Lena Nakamura is also in the list: the second Entrepreneurship enrollment in her transcript belongs to this section.
Five tables and grouping: in the 2026-Fall term, how many enrollments did the students of each department make? The department name is reached through the student, and the term name through the section.
SELECT d.name AS department, COUNT(*) AS enrollments FROM enrollment e JOIN student s ON s.id = e.student_id JOIN department d ON d.id = s.department_id JOIN course_offering o ON o.id = e.offering_id JOIN term t ON t.id = o.term_id WHERE t.name = '2026-Fall' GROUP BY d.name ORDER BY enrollments DESC;
| department | enrollments |
|---|---|
| Psychology | 63 |
| Business Administration | 61 |
| Software Engineering | 55 |
| Management Information Systems | 40 |
| Computer Programming | 37 |
| Industrial Engineering | 31 |
| New Media and Communication | 23 |
All JOINs go from the many side to the one side, so each row is still one enrollment, and COUNT(*) counts enrollments.
In the Earbud music app (earbud.sql), the songs liked by the listener with the nickname night_owl, and their artists. The path is song_like → song → artist; to filter by nickname, listener also joins the chain.
SELECT s.title AS song, a.name AS artist FROM song_like l JOIN listener k ON k.id = l.listener_id JOIN song s ON s.id = l.song_id JOIN artist a ON a.id = s.artist_id WHERE k.nickname = 'night_owl' ORDER BY l.liked_on;
| song | artist |
|---|---|
| Blue Hour | Asphalt Verse |
| Balcony at Five | Asphalt Verse |
| Coffee Stain | Salt Pier |
| Platform Three | Broken Compass |
The artist table was joined to song, not to song_like: a like has no artist number, but a song does.
cpON p.id = c.prerequisite_idprerequisite_id