…
…
SQL and Database Fundamentals · Lesson 18 / 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 president's office sent you a department report from the previous intern. It says Software Engineering has 80 students and 80 instructors, but the department has 20 students and 4 instructors. The query gives no error, yet the report does not add up, so you will find where the numbers got inflated and fix the report.
Here is the intern's report next to the real numbers:
| Department | Students in report | Instructors in report | Real students | Real instructors |
|---|---|---|---|---|
| Software Engineering | 80 | 80 | 20 | 4 |
| Business Administration | 96 | 96 | 24 | 4 |
| New Media and Communication | 20 | 20 | 10 | 2 |
The numbers in the report are not made up. They are the real output of the intern's query. The query runs without problems and PostgreSQL gives no warning. And 80 students is not a strange number for a department. If nobody in the president's office knew the department, this report would go into the archive without anyone noticing. This lesson is about exactly this kind of mistake: a number that gives no message, looks reasonable, and is wrong. In the last three lessons you learned to join tables. In this lesson you will see why numbers inflate when you summarize a joined result, and how to catch it.
In this lesson you will:
Look at the table once more. Software Engineering has 20 students and 4 instructors, and the report says 80. Business Administration has 24 students and 4 instructors, and the report says 96.
The department has 20 students and 4 instructors, and the report shows 80. Where could 80 come from?
The shortest way to understand a wrong summary is to look at the rows before summarizing. COUNT and GROUP BY swallow rows. To see what you are counting, remove them for a moment and list the raw rows the join produces. Let's do this for a small department: New Media and Communication (id 6) has 10 students and 2 instructors (Kim and Cohen). We write the same join as the intern's query, only for this department and without counting.
-- Example 1: Three-table join for one department, without summarizing SELECT s.id, s.first_name, s.last_name, i.last_name AS instructor FROM department d JOIN student s ON s.department_id = d.id JOIN instructor i ON i.department_id = d.id WHERE d.id = 6 ORDER BY s.id, i.id;
Result (first 6 of 20 rows):
| id | first_name | last_name | instructor |
|---|---|---|---|
| 5 | Felix | Ortiz | Kim |
| 5 | Felix | Ortiz | Cohen |
| 11 | Liam | Lindqvist | Kim |
| 11 | Liam | Lindqvist | Cohen |
| 18 | Greta | Cohen | Kim |
| 18 | Greta | Cohen | Cohen |
(20 rows)
There are 10 students, but 20 rows came back. Every student is written twice. Think step by step about why. When department and student are joined, the department row is written once for each of its students: 10 rows. You saw this in lesson 15. Now each of these 10 rows is matched with instructor. The condition is i.department_id = d.id, so all instructors of the department match every row. The department has 2 instructors, so every row is written twice: 10 × 2 = 20. A JOIN produces one row for every matching pair. The more matches there are, the more the rows multiply.
In lesson 17, when you made the chain longer, you saw that the row count stayed at 781. That chain always went from the "many" side to the "one" side: every enrollment has one offering, every offering has one course and one term. When a row finds only one match in the other table, the row count does not change. Here the direction is the opposite. A department has many students and many instructors. student and instructor are both linked to the same department, but they have no relationship with each other. When two separate "many" tables are linked to the same "one" table at once, the rows are not added. They are multiplied.
The query is ready in the cell below. Run it first and look at how many times the same student number appears. Then delete the , i.last_name AS instructor part in the first line and the JOIN instructor line, change the ORDER BY line to ORDER BY s.id;, and run it again. The row count goes down to 10: each student appears once.
Try it now· not graded; doesn't affect progress
The false belief that falls in this step is: "A JOIN only adds columns, never rows." This sentence is true only when every row has exactly one match in the other table. If a row has three matches, you get three rows. If it has no match, INNER JOIN removes it. Adding columns is the visible side of a JOIN. Changing the row count is the hidden side.
When the intern wrote COUNT(s.id), they thought they were counting students. But COUNT does not count students. It counts rows, and every row where s.id is filled counts as one. If the rows were students, the result would be right. But the rows of this join are not students. They are student-instructor pairs. The 20 students and 4 instructors of Software Engineering make 80 pairs, and COUNT counts 80 pairs.
So before you summarize, ask yourself one question: "What does one row of this query stand for?" We will call this the grain of the result: is one row a student, an enrollment, or a student-instructor pair? In the result of student JOIN department, one row is one student, because every student has one department. In the result of course_offering JOIN enrollment, one row is not an offering but an enrollment: offering 1 has 8 enrollments, so this offering appears 8 times in the result. The grain is the row of the "most many" side of the join. If there are two separate "many" sides, the grain is the pair of them.
In each join, what does one row of the result stand for?
For each row, pick its match from the list, then check.
student s JOIN department d ON d.id = s.department_iddepartment d LEFT JOIN student s ON s.department_id = d.idcourse_offering o JOIN enrollment e ON e.offering_id = o.idenrollment e JOIN course_offering o ON o.id = e.offering_id JOIN course c ON c.id = o.course_iddepartment d JOIN student s ON s.department_id = d.id JOIN instructor i ON i.department_id = d.idThe nice thing about the grain question is that you can ask it without running anything. Read the FROM and JOIN lines and think "how many Y does every X have?" If the answer conflicts with a numeric summary, for example if the row is a student-instructor pair and you want the number of students, the query counts wrong however clean it looks.
Multiplication does not break only COUNT. SUM and AVG also work on rows. If the same row is written three times, its value is added three times. Let's see this with the total capacity per term. Capacity is a property of the offering: in the course_offering table, every offering has one capacity.
-- Example 2: Total capacity per term SELECT t.name AS term, SUM(o.capacity) AS total_capacity FROM term t JOIN course_offering o ON o.term_id = t.id GROUP BY t.id, t.name ORDER BY t.id;
| term | total_capacity |
|---|---|
| 2025-Fall | 870 |
| 2026-Spring | 660 |
| 2026-Fall | 870 |
(3 rows)
The grain in this query is the offering. When term and course_offering are joined, every offering becomes one row, because every offering has one term. This result is correct. Now someone says "let's add the number of enrollments of each term too" and joins the enrollment table to the query.
If the line JOIN enrollment e ON e.offering_id = o.id is added to the query above, what does the total capacity of 2025-Fall become?
SELECT t.name AS term, SUM(o.capacity) AS total_capacity FROM term t JOIN course_offering o ON o.term_id = t.id JOIN enrollment e ON e.offering_id = o.id GROUP BY t.id, t.name ORDER BY t.id;
In the cell below, the JOIN enrollment line is a comment. Run it as it is first. Then delete the -- at the start of the line and run it again. Then put the mark back. The numbers change even though you never touched the capacity column.
Try it now· not graded; doesn't affect progress
With JOIN enrollment open, the result is:
| term | total_capacity |
|---|---|
| 2025-Fall | 10620 |
| 2026-Spring | 10500 |
| 2026-Fall | 13950 |
(3 rows)
10620 instead of 870. Offering 48 has a capacity of 40 and 79 enrollments. By itself, this offering adds 79 × 40 = 3160 to the total instead of 40. The false belief here is "SUM and COUNT are not affected by a join." Aggregate functions work after the join, on the rows the join produced. In the earlier query, SUM saw each offering once. Now it sees the same offering as many times as it has enrollments.
It is not always easy to catch multiplication by eye. You cannot read 342 rows one by one. So before every summary that includes a join, make three counts:
1. Count before the JOIN: how many of the thing you want to count are there on their own? (SELECT COUNT(*) FROM student; → 120)
2. Count after the JOIN: how many rows does the join produce?
3. In the same query, compare COUNT(*) with COUNT(DISTINCT key): is the row count equal to the number of distinct keys of the thing you want to count?
In lesson 11 you saw the difference between COUNT(*) and COUNT(column): one counts all rows, the other counts the rows where the column is filled. COUNT(DISTINCT column) counts each different value once. A primary key identifies every record on its own, so COUNT(DISTINCT s.id) counts each student once, however many copies there are. If the row count and the distinct key count are equal, there is no multiplication. If they are different, the grain is not what you think it is.
-- Example 3: Checking query SELECT COUNT(*) AS row_count, COUNT(DISTINCT s.id) AS students FROM department d JOIN student s ON s.department_id = d.id JOIN instructor i ON i.department_id = d.id;
| row_count | students |
|---|---|
| 342 | 120 |
(1 row)
342 rows, 120 distinct students. On average, every student is written three times. The rows are not students but student-instructor pairs. When you remove the instructor line, COUNT(*) goes down to 120 and the two numbers become equal. This check takes one minute, and it would have caught the intern's report before it went to the president's office. Below, the lines of the same checking query are mixed up. Put them in the right order.
Put the lines of the checking query in the right order.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
The second false belief falls here: "A number that gives no error and looks reasonable is correct." PostgreSQL looks at the syntax and the tables. It cannot know what you want to count. 80 students looked reasonable, so nobody noticed the mistake. Looking reasonable is not proof of being correct. Proof is getting the same number another way, for example with a count that has no JOIN.
After you find the inflation, there are three ways to fix it, and the question itself decides which one to choose.
| Question | What to do | Example |
|---|---|---|
| Is that table needed for the question? No | Remove the JOIN | enrollment is not needed in the capacity query: remove it, and you get 870 / 660 / 870 |
| Needed, but you are counting the thing it multiplies | Count the key as distinct: COUNT(DISTINCT key) | Students and instructors in the same department report: COUNT(DISTINCT s.id), COUNT(DISTINCT i.id) |
Needed, and it is an inflated total (SUM) | Split the question into two separate queries | Capacity per term is one query, the enrollment count is a separate query |
In the capacity example, the first way is enough. The answer to "total capacity per term" is not in the enrollment table, and enrollment only multiplies. Removing an unneeded JOIN is the cleanest fix. In the department report, both tables are needed, because the report wants both the number of students and the number of instructors. There we count the keys as distinct. The president's office wants to see all eight departments, so Data Science and Analytics, which has no students, must be in the list too. For this, we make both JOINs LEFT.
-- Example 4: Fixed department report SELECT d.name AS department, COUNT(DISTINCT s.id) AS students, COUNT(DISTINCT i.id) AS instructors FROM department d LEFT JOIN student s ON s.department_id = d.id LEFT JOIN instructor i ON i.department_id = d.id GROUP BY d.id, d.name ORDER BY d.id;
| department | students | instructors |
|---|---|---|
| Computer Programming | 14 | 3 |
| Software Engineering | 20 | 4 |
| Industrial Engineering | 12 | 2 |
| Business Administration | 24 | 4 |
| Management Information Systems | 17 | 2 |
| New Media and Communication | 10 | 2 |
| Psychology | 23 | 2 |
| Data Science and Analytics | 0 | 1 |
(8 rows)
Look at the Data Science row. The department has no students, and the LEFT JOIN keeps it with one row where s.id is NULL. COUNT(DISTINCT s.id) does not count NULL, so it gives 0. The COUNT(*) trap from lesson 16 applies here too: if you wrote COUNT(*), it would give 1. Let's clear one more false belief here: "LEFT JOIN does not multiply." LEFT JOIN only keeps the rows that have no match. The matching rows multiply just as in INNER JOIN. If you delete the DISTINCT words in the same query, Data Science shows 0 and 1, but Software Engineering is still 80 and 80.
The intern's query is in the cell below. Run it first and see the inflated report with 7 rows. Then fix the two COUNTs and compare the numbers with the table above. Finally, make both JOINs LEFT JOIN and see whether the eighth row appears.
Try it now· not graded; doesn't affect progress
The third way, splitting the question into two queries, means two separate result tables for now: one for capacity per term, the other for the enrollment count per term. The clean way to bring them together in one table is "first summarize each table on its own, then join the summaries." You will do this with a subquery in FROM in lesson 21 and with WITH in lesson 23. We will come back to this report in those lessons.
Multiplication appears in the same way in every database. Think of a small online store. Maya placed an order. The order has three products (items), and Maya paid the amount in two equal installments. Three small tables:
orders
| id | customer |
|---|---|
| 1 | Maya |
order_item
| id | order_id | product | amount |
|---|---|---|---|
| 1 | 1 | Notebook | 4 |
| 2 | 1 | Pen set | 3 |
| 3 | 1 | Backpack | 15 |
payment
| id | order_id | installment | amount |
|---|---|---|---|
| 1 | 1 | 1 | 11 |
| 2 | 1 | 2 | 11 |
The order total is $22, and the amount paid is $22. order_item and payment are both linked to orders, but they have no relationship with each other: like the students and instructors in the case.
If the three tables orders, order_item, and payment are joined in this order and SUM(p.amount) is taken, how many times the real value does the total of the payments come out?
SELECT SUM(p.amount) AS paid FROM orders o JOIN order_item i ON i.order_id = o.id JOIN payment p ON p.order_id = o.id;
The rows of the join and the two totals:
-- Example 5: Store (outside the case) SELECT SUM(i.amount) AS items, SUM(p.amount) AS paid FROM orders o JOIN order_item i ON i.order_id = o.id JOIN payment p ON p.order_id = o.id;
| items | paid |
|---|---|
| 44 | 66 |
(1 row)
Both totals are wrong, and they are inflated by different amounts: the items 2 times (the number of installments), the payments 3 times (the number of items). The total of one table is multiplied by the number of matches in the "many" table next to it. The fix again comes from the question: for the question "total paid," the order_item table is not needed. SELECT SUM(p.amount) FROM orders o JOIN payment p ON p.order_id = o.id; returns 22.
Multiplication is not always a mistake. The mistake is counting a row whose grain is wrong. For a dean who wants both the number of enrollments and the number of students with enrollments for each department, the same join answers two different questions correctly. The grain is the enrollment: COUNT(*) counts enrollments, and COUNT(DISTINCT s.id) counts students.
SELECT d.name AS department, COUNT(*) AS enrollment_count, COUNT(DISTINCT s.id) AS students FROM department d JOIN student s ON s.department_id = d.id JOIN enrollment e ON e.student_id = s.id GROUP BY d.id, d.name ORDER BY d.id;
| department | enrollment_count | students |
|---|---|---|
| Computer Programming | 82 | 14 |
| Software Engineering | 148 |
"Fixing" an inflated total with `SUM(DISTINCT ...)`. COUNT(DISTINCT s.id) fixed the report. Someone who tries to fix the inflated capacity with DISTINCT in the same way writes this:
SELECT t.name AS term, SUM(DISTINCT o.capacity) AS total_capacity FROM term t JOIN course_offering o ON o.term_id = t.id JOIN enrollment e ON e.offering_id = o.id GROUP BY t.id, t.name ORDER BY t.id;
| term | total_capacity |
|---|---|
| 2025-Fall | 180 |
| 2026-Spring | 180 |
| 2026-Fall | 180 |
(3 rows)
Every term shows 180. The right answers are 870, 660, and 870. SUM(DISTINCT o.capacity) adds the different capacity values
COUNT, SUM, and AVG work on these rows, so they inflate. A LEFT JOIN multiplies the matching rows too.COUNT(*) with COUNT(DISTINCT key). Many more rows than expected means multiplication or a wrong ON condition. Fewer rows than expected means an INNER JOIN removed rows with no match.SUM(DISTINCT ...). Split the question into two queries instead.Next lesson: In the unit workshop you will use this check from start to finish while writing a term report on the Earbud dataset, and then in lesson 20 you will solve a question in two steps with subqueries.
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.
| Industrial Engineering | 81 | 12 |
| Business Administration | 155 | 23 |
| Management Information Systems | 88 | 16 |
| New Media and Communication | 68 | 10 |
| Psychology | 159 | 23 |
(7 rows)
Of the 20 students of Software Engineering, 19 appear: the student with no enrollments dropped out in the INNER JOIN. This query answers "students with enrollments." It does not answer "students in the department."
In the Earbud music app (earbud.sql), when you join artists with their songs and songs with their plays, the grain is one play. COUNT(s.id) looks like the number of songs, but it gives the number of plays. To count the songs, you need to count the key as distinct.
SELECT a.name AS artist, COUNT(*) AS row_count, COUNT(s.id) AS song_column, COUNT(DISTINCT s.id) AS played_songs FROM artist a JOIN song s ON s.artist_id = a.id JOIN play p ON p.song_id = s.id GROUP BY a.id, a.name ORDER BY a.id;
| artist | row_count | song_column | played_songs |
|---|---|---|---|
| Salt Pier | 40 | 40 | 5 |
| Prairie Strings | 18 | 18 | 3 |
| Broken Compass | 70 | 70 | 8 |
| Misty Valley | 6 | 6 | 2 |
| Neon Heron | 30 | 30 | 3 |
| Asphalt Verse | 46 | 46 | 5 |
| Purple Tortoise | 7 | 7 | 1 |
(7 rows)
Salt Pier has 7 songs, and 5 of them were played at least once. 40 is the number of plays. COUNT(s.id) and COUNT(*) give the same result, because both count rows.
COUNT(DISTINCT s.id)s.idDISTINCTenrollment