…
…
SQL and Database Fundamentals · Lesson 14 / 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.
The registrar's office wants names instead of numbers in the end-of-term report: the student's name, the name of their department, and the last name of their advisor. These three facts sit in three separate tables, and the tables are connected only by numbers. Before you write the report, you will draw the map: which table connects to which, and through which column?
By the end of this unit you will hand the registrar a table like this one. Here are its first three rows:
| first_name | last_name | department | advisor |
|---|---|---|---|
| Felix | Abara | Business Administration | Popescu |
| Lena | Nakamura | Business Administration | Singh |
| Maya | Rossi | Software Engineering | Reyes |
This table does not exist in the database. The student's name is in the student table, the department's name is in the department table, and the advisor's last name is in the instructor table. The student table has no text such as "Business Administration" or "Popescu"; there are only numbers in their place. To bring three tables together in one result, you first need to know what those numbers point to. In this lesson you will not learn a new way to write queries. With WHERE, GROUP BY, and COUNT, which you already know, you will follow the links between tables with your own eyes. You will join them in one query in the next lesson.
In this lesson you will:
In lesson 2 you saw that every table has a primary key: the id column identifies each row on its own and never repeats a value. Now look at the department_id column in the student table. This column is not a property of the student; it is the number of a row in another table. Instead of writing the department name again and again in each of the 120 student rows, only the department's number is written, and the name stays in one place, in the department table. If the department's name changes, updating one row is enough.
A column that holds a value from another table's primary key is called a foreign key. The word "foreign" comes from the value belonging to another table: department_id sits in the student table but points to the id of the department table.
Let's try following an address with one student. Student 17 is Lena Nakamura. First we fetch her row by primary key. A search by primary key always returns at most one row.
-- 1. Find the student's row by primary key SELECT id, first_name, last_name, department_id FROM student WHERE id = 17;
| id | first_name | last_name | department_id |
|---|---|---|---|
| 17 | Lena | Nakamura | 4 |
(1 row)
department_id is 4. This is an address: it says "go to the row in the department table whose id is 4." In the second query we search for this value in the primary key of the department table.
-- 2. Look up the number from the address in the department table's primary key SELECT id, name, faculty FROM department WHERE id = 4;
| id | name | faculty |
|---|---|---|
| 4 | Business Administration | Faculty of Business and Management |
(1 row)
Lena studies Business Administration. The bridge between the two queries was you: you read the 4 in the result of the first query and typed it into the WHERE line of the second. A join (JOIN) lets the database do this carrying for you; but writing a JOIN without knowing what is being carried is like knocking on a door without reading the address.
In the cell below, two steps are ready. Because the cell on the site shows only the result of the last query, the second query is left as a comment. First run it and read department_id. Then write another student number instead of 17 (for example 42 or 100), replace the 4 in the second query with the number you found, delete the -- at the start of the line, and run it again.
Try it now· not graded; doesn't affect progress
When following a link, the most common mistake is searching with the wrong number. Every table has a column named id, and because they all have the same name, they look as if they point to the same thing. But each id numbers only the rows of its own table. If a student's id is 3, that means "student number 3"; it has nothing to do with department number 3. The address that leads to the department is not in the student's id but in the department_id column.
The row of student 3, Felix Abara, looks like this: id 3, department_id 4, advisor_id 11. You want to find his department.
To find the department name of student 3, which id do you search for in the department table?
SELECT id, first_name, last_name, department_id FROM student WHERE id = 3; -- Result: 3 | Felix | Abara | 4
A foreign key is not just a habit; it is a rule that the database enforces. When the student table was defined, the rule "the value must exist in the id of the department table" was placed on the department_id column. For this reason, you cannot write a number that is not in the department table. If you try to add a student to a department that does not exist, PostgreSQL rejects the insert. The address must always point to a row that exists; this is called referential integrity. Thanks to this rule, you never fall into a gap when you follow an address. You will learn to write this rule yourself when you create tables in lesson 30.
Why would a row that puts 99 in the student.department_id column be rejected?
The relationship between student and department has a name. Many students study in one department, but each student has only one department. This is called a one-to-many (1-N) relationship. The foreign key always sits in the table on the "many" side: department_id is in the student table. Think of the opposite: if you tried to put the foreign key in the department table, you would have to write the numbers of 24 students into the Business Administration row. But a cell holds a single value. Each row on the "many" side holds a single address, and there is no problem.
To see this in the data, use the grouped count you learned in lesson 12: group the students by department_id and count them.
SELECT department_id, COUNT(*) AS students FROM student GROUP BY department_id ORDER BY department_id;
| department_id | students |
|---|---|
| 1 | 14 |
| 2 | 20 |
| 3 | 12 |
| 4 | 24 |
| 5 | 17 |
| 6 | 10 |
| 7 | 23 |
(7 rows)
This small table tells you three things. First, the value of a foreign key repeats: the value 4 appears in exactly 24 rows, because Business Administration has 24 students. A primary key never repeats, but repeating is normal for a foreign key; it is in fact what a one-to-many relationship is. Second, many student rows are linked to one department row: the "many" side is here. Third, there are 7 groups, but the department table has 8 departments. Department 8, Data Science and Analytics, was founded this year and has no students yet. A foreign key says "every student must have a department that exists"; it does not say "every department must have students."
All the links in the case database are in the diagram below. Each arrow goes from the table on the "many" side to the table on the "one" side, and the name of the foreign key column is written on the arrow.
The same information as a table:
| Table | What it holds | Rows | Foreign keys |
|---|---|---|---|
department | Departments and their faculties | 8 | none |
instructor | Instructors and their titles | 20 | department_id → department |
student | Students | 120 | department_id → department, advisor_id → instructor |
course | Course catalog | 33 | department_id → department, prerequisite_id → course |
term | Academic terms |
Note two things. The name of a foreign key is often the name of the table it points to plus _id (department_id, course_id), but not always: advisor_id points to the instructor table. Do not guess the name; look at the schema. The second is that an arrow leaving the course table returns to course: prerequisite_id holds the id of another course that is a prerequisite of this one. A table can refer to itself too.
The last misconception about foreign keys is that they must always be filled in. Remember from lesson 7: NULL means "no value." A foreign key can be NULL; this means "this row has no address right now." The rule only asks that a filled-in value point to a row that exists. In the cell below, make the same count for advisor_id and look at the NULL group.
Try it now· not graded; doesn't affect progress
In the last row of the result, advisor_id is empty and the count is 8: eight students have not been assigned an advisor yet. Of the 20 instructors, 19 advise at least one student; instructor 18 is not in the list, because no student's address points to them. Now match the other foreign keys in the diagram with the tables they point to.
Which table's primary key does each foreign key column point to?
For each row, pick its match from the list, then check.
student.advisor_idcourse.prerequisite_idenrollment.offering_idcourse_offering.term_idcourse_offering.instructor_idThe relationship between students and courses is different. A student takes many courses, and many students take a given section. There is a "many" in both directions. This is called a many-to-many (N-M) relationship. You cannot build this relationship by putting a single foreign key between two tables, because whichever side you put it on, you would have to write several addresses into a single cell on that side.
Does adding a column named course_id to the student table solve the problem of a student taking more than one course?
The solution is a third table. In the case database, this table is enrollment. Each of its rows is a "slip": it says "this student is enrolled in this section." student_id points to the student, and offering_id points to the section. A table like this, which has two foreign keys and connects two tables, is called a junction table. A junction table splits a many-to-many relationship into two one-to-many relationships: a student has many slips, a section has many slips, but each slip belongs to a single student and a single section.
Let's prove the claim "many in both directions" by counting the data. First the student direction: group enrollment by student_id. Because some students have the same number of enrollments, we added a second sort column; the result is the same on every run.
-- 1. Student direction: the students with the most enrollments SELECT student_id, COUNT(*) AS enrollment_count FROM enrollment GROUP BY student_id ORDER BY enrollment_count DESC, student_id LIMIT 3;
| student_id | enrollment_count |
|---|---|
| 48 | 11 |
| 88 | 11 |
| 6 | 10 |
(3 rows)
If you run the same query with ORDER BY enrollment_count, student_id, you see the students with the fewest enrollments: at least 2. So a student who has enrollments is enrolled in between 2 and 11 sections (3 of the 120 students have no enrollments at all; they never appear in the enrollment table, so they do not show up in the groups either). Now the section direction: group the same table by offering_id this time.
-- 2. Section direction: the most crowded sections SELECT offering_id, COUNT(*) AS enrollment_count FROM enrollment GROUP BY offering_id ORDER BY enrollment_count DESC, offering_id LIMIT 3;
| offering_id | enrollment_count |
|---|---|
| 48 | 79 |
| 47 | 77 |
| 52 | 51 |
(3 rows)
In reverse order, the section with the fewest enrollments has 2. A section that has enrollments has between 2 and 79 students. More than one in both directions: the relationship is many-to-many, and enrollment is the junction table. In a one-to-many relationship you could not make this count for the "one" side; for example, if you counted a student's departments, the answer would always be 1 for every student.
Now you can find from the schema which tables to pass through to answer a question. The method: first find which table holds the answer, then go from the table you start in to that table by following the arrows. You cannot skip any table on the path, because the table you skip is the one that holds the address leading to the next one.
Example question: "What is the name of the course a student takes?" The course's name is in the course table. There is no direct arrow between student and course. You go from student to enrollment (the slips), from enrollment to course_offering (the section), and from course_offering to course (the name in the catalog). You cannot skip course_offering: the slip holds the section's number, not the course's; the same course is offered in different terms with different sections.
Put the tables to pass through for "the name of the course a student takes" in path order.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
Apply the same method to every question. Choose the right path for the questions below.
Match each question with the path of tables to follow to answer it.
For each row, pick its match from the list, then check.
The same way of thinking works in every database. Imagine a small music app called Earbud. It has artists, songs, and listeners; listeners like songs. A few rows from three tables:
artist
| id | name | genre |
|---|---|---|
| 1 | Salt Pier | pop |
| 3 | Broken Compass | rock |
| 7 | Asphalt Verse | rap |
song
| id | title | artist_id |
|---|---|---|
| 1 | Platform Three | 3 |
| 2 | Coffee Stain | 1 |
| 3 | Yellow Bus | 3 |
| 8 | Salt and Lemon | 1 |
song_like
| listener_id | song_id |
|---|---|
| 1 | 1 |
| 1 | 2 |
| 10 | 1 |
| 10 | 3 |
| 22 | 2 |
song.artist_id is a foreign key: each song has one artist, and an artist has many songs. Broken Compass (3) has two songs in view. This is a one-to-many relationship, and the foreign key is again on the "many" side, in the song table. Likes are many in both directions: listener 1 liked two songs (1 and 2), and song 1 was liked by two listeners (1 and 10). This is a many-to-many relationship, and song_like is its junction table: each row is a slip linking a listener to a song.
You can classify everyday relationships with the same question: "How many B can an A have, and how many A can a B have?" If both answers are "many," you need a junction table. If both answers are "one," the relationship is one-to-one; you will see this in lesson 31 when you model data.
Match each everyday relationship with its type.
For each row, pick its match from the list, then check.
Which course and which term does enrollment 99, which belongs to student 17, refer to? Path: enrollment → course_offering → course and term. At each step you carry the number from the previous result.
-- 1. The section number of the enrollment SELECT id, student_id, offering_id FROM enrollment WHERE id = 99;
| id | student_id | offering_id |
|---|---|---|
| 99 | 17 | 24 |
-- 2. The course and term numbers of the section SELECT id, course_id, term_id, instructor_id FROM course_offering WHERE id = 24;
| id | course_id | term_id | instructor_id |
|---|---|---|---|
| 24 | 15 | 1 | 11 |
id, code, name course id = 15; id, name term id = 1;
Following the link with the wrong key. Someone who wants to find the department of student 3 searches for the student's id directly in the department table:
SELECT name FROM department WHERE id = 3;
| name |
|---|
| Industrial Engineering |
(1 row)
PostgreSQL does not raise an error; the query runs perfectly and returns a department name. But this is the name of department 3, not the department of student 3. In Felix Abara's row, department_id says 4; the correct query is SELECT name FROM department WHERE id = 4; and the result is Business Administration. Because no error message appears, you can catch this mistake only by checking the address yourself: did the number you are searching for come from the foreign key column of the row you started with?
id, not the id of the row you started with. Referential integrity does not allow an address that does not exist; but a foreign key can repeat and can be NULL.student.department_id); a many-to-many relationship is built with a junction table that has two foreign keys (enrollment). To understand the type, group the relationship in both directions and count.Next lesson: You followed the link by hand with two separate queries; INNER JOIN does the same job in one query and puts the student's name next to their department's name.
Exercises and quiz are for members
This lesson has 6 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
| none |
course_offering | A course offered in a term (a section) and its instructor | 54 | course_id → course, term_id → term, instructor_id → instructor |
enrollment | The section a student took, and the grades | 781 | student_id → student, offering_id → course_offering |
Result (two queries, in order):
| id | code | name |
|---|---|---|
| 15 | BUS101 | Introduction to Business |
| id | name |
|---|---|
| 1 | 2025-Fall |
Enrollment 99 is Lena's Introduction to Business course in the 2025-Fall term. You wrote four queries; in lesson 17 you will build the same path in a single query.
In the Earbud database (earbud.sql, which you will use in the last exercise at the end of the lesson), you can count a one-to-many relationship with the same method: group the songs by artist_id.
SELECT artist_id, COUNT(*) AS songs FROM song GROUP BY artist_id ORDER BY artist_id;
| artist_id | songs |
|---|---|
| 1 | 7 |
| 2 | 4 |
| 3 | 8 |
| 4 | 2 |
| 5 | 3 |
| 7 | 5 |
| 8 | 1 |
(7 rows)
The artist table has 8 artists but the count produced 7 groups: artist 6 has no songs yet. It is the same as the department with no students in the case.