…
…
SQL and Database Fundamentals · Lesson 16 / 41 · Joins
PreviewIn this lesson you will
LEFT JOIN ... WHERE right.id IS NULL patternYou can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
At the department heads' meeting, three questions came up: is there a department with no students, is there a course that was never offered, and is there a student who never enrolled in any course? The JOIN you wrote in the last lesson silently drops rows that have no match, so the answers to these questions are exactly the rows that fell out of the result. In this lesson you will bring those rows back and find what is missing.
At the end of lesson 15, you counted students per department name:
SELECT b.name, COUNT(o.id) AS students FROM department b JOIN student o ON o.department_id = b.id GROUP BY b.name ORDER BY students;
| name | students |
|---|---|
| New Media and Communication | 10 |
| Industrial Engineering | 12 |
| Computer Programming | 14 |
| Management Information Systems | 17 |
| Software Engineering | 20 |
| Psychology | 23 |
| Business Administration | 24 |
(7 rows)
The university has 8 departments, but the table shows 7 rows. Data Science and Analytics was founded this year and has no students yet. INNER JOIN found no matching student row for this department, so it removed the department from the result, with no warning. The first question at the meeting was "is there a department with no students?" The answer is yes, but this query hides it. To find what is missing, you need the rows that INNER JOIN throws away.
In this lesson you will:
The course catalog has 33 courses. Four of them (GEN101 to GEN104) are shared by all departments, so their department_id is NULL. On the other side, the Data Science department has no course in the catalog yet. So both sides have rows without a match: 4 courses with no department and 1 department with no courses. Let's run the query that lists courses with department names three times, changing only the JOIN keyword.
Example 1 (case): Three join types, three row counts
SELECT d.code, d.name, b.name AS department FROM course d JOIN department b ON b.id = d.department_id;
Result: 29 rows. If you write LEFT JOIN instead of JOIN in the same query, you get 33 rows.
| Written as | Rows | Which rows |
|---|---|---|
course d JOIN department b | 29 | Only courses that have a department |
course d LEFT JOIN department b | 33 | Every course in the catalog; department is empty for the 4 shared courses |
INNER JOIN (JOIN for short) returns the rows that have a match in both tables. LEFT JOIN keeps every row of the left table, the one written in FROM: if a match exists, it joins as usual; if not, it still puts the row in the result and fills the right table's columns with NULL. The 4 extra rows (29 to 33) are the shared courses that have no department. There is a third type: FULL JOIN keeps every row of both tables.
The same query gave 29 rows with JOIN and 33 rows with LEFT JOIN. How many rows does it give with FULL JOIN?
SELECT d.code, d.name, b.name AS department FROM course d FULL JOIN department b ON b.id = d.department_id;
Now try it yourself. The query in the cell uses INNER JOIN. Run it and look at the row count under the result. Then change JOIN to LEFT JOIN and run it again, and finally change it to FULL JOIN. The row count changes each time. Scroll to the bottom of the result and find the rows where department or code is empty: those are the extra rows.
Try it now· not graded; doesn't affect progress
FULL JOIN gives 34 rows: 29 matched, 4 courses with no department, and one row where code and name are empty and department says "Data Science and Analytics". All three types use the same ON condition; the only difference is what happens to the rows that do not match.
In LEFT JOIN, the word "left" has nothing to do with the size or importance of a table; it only describes the order you write them in. The table right after FROM is the left one, and the table after JOIN is the right one. You write the table you want to see in full in FROM. The first question at the meeting starts with "all departments", so department must be on the left.
Example 2 (case): All departments and their student counts
SELECT b.name, COUNT(o.id) AS students FROM department b LEFT JOIN student o ON o.department_id = b.id GROUP BY b.name ORDER BY students;
| name | students |
|---|---|
| Data Science and Analytics | 0 |
| New Media and Communication | 10 |
| Industrial Engineering | 12 |
| Computer Programming | 14 |
| Management Information Systems | 17 |
| Software Engineering | 20 |
| Psychology | 23 |
| Business Administration | 24 |
(8 rows)
All eight departments are here, and Data Science is at the top with 0 students. It helps to look at the result before the grouping. If you delete the GROUP BY and COUNT lines and write SELECT b.name, o.first_name, you get 121 rows. Why not 8? A department produces as many rows as it has students: Business Administration gives 24 rows, Psychology gives 23. Why not 120? All 120 students have a department, which makes 120 rows, and Data Science is added as one row with empty student columns. 120 + 1 = 121. LEFT JOIN does not keep the row count of the left table; it guarantees that every left row appears at least once.
LEFT JOIN also has a mirror image: RIGHT JOIN keeps every row of the right table. Match the four types with the rows they return.
Which rows does each join return?
For each row, pick its match from the list, then check.
INNER JOIN (or just JOIN)LEFT JOINRIGHT JOINFULL JOINThe second and third questions at the meeting want a list, not a number: "which students never enrolled in a course?" For this you use the trace that LEFT JOIN leaves behind. In every unmatched row, the right table's columns are NULL. So if you do a LEFT JOIN and keep only the rows where the right table's primary key is NULL, only the unmatched rows are left.
Example 3 (case): Students with no enrollments
SELECT o.student_no, o.first_name, o.last_name, o.year FROM student o LEFT JOIN enrollment k ON k.student_id = o.id WHERE k.id IS NULL;
| student_no | first_name | last_name | year |
|---|---|---|---|
| 202402002 | Yuki | Johansson | 3 |
| 202405006 | Mohammed | Cohen | 3 |
| 202504003 | Hiro | Kim | 2 |
(3 rows)
Think it through step by step. student LEFT JOIN enrollment produces 784 rows: 781 enrollment rows (each enrollment matches its student) and one row each for the 3 students with no enrollment. In these three rows, all the enrollment columns such as k.id and k.midterm are NULL. WHERE k.id IS NULL keeps only these three rows. Remember from lesson 7: you ask about NULL with IS NULL, not = NULL; k.id = NULL is never true in any row, and the query returns nothing.
The same pattern works for every "no ..." question: courses never offered, instructors who never taught, customers who never ordered. Put the lines of the query that answers the meeting's second question in order.
Put the query that returns the code and name of courses that were never offered in order.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
The column you check for NULL in this pattern is the right table's primary key (k.id, a.id). This is not a habit, it is a requirement. A NULL you see in the result can mean two things: either the row never matched, or it matched but the value in that column really is empty in the data. A primary key can never be empty, so a NULL there only means "no match".
In lesson 11 you saw the difference between COUNT(*) and COUNT(column): COUNT(*) counts rows, and COUNT(column) counts the values in that column that are not NULL. In an outer join, this difference decides whether the result is right or wrong. In Example 2 we wrote COUNT(o.id) and Data Science came out as 0. What if we had written COUNT(*) in the same query?
What shows up in the students column for Data Science and Analytics, which has no students?
SELECT b.name, COUNT(*) AS students FROM department b LEFT JOIN student o ON o.department_id = b.id GROUP BY b.name;
The result is 1, and this mistake is easy to miss: the counts of the other seven departments are correct, and only the department with no students looks wrong. When you count with an outer join, the rule is: count the right table's primary key.
A new question comes from the meeting: "How many scholarship students does each department have? A department with no scholarship students should be in the list with 0." It looks enough to take Example 2 and add a scholarship condition. Write the condition in WHERE out of habit, and see what happens in the cell below. The o.has_scholarship column holds a true/false value; WHERE o.has_scholarship keeps the rows where it is true.
Try it now· not graded; doesn't affect progress
The first run gives 7 departments; Data Science is missing again. Here is why: LEFT JOIN produced a row for Data Science with NULL student columns, but then WHERE ran. In this row o.has_scholarship is NULL, and as you know from lesson 7, NULL does not satisfy a condition, so the row is removed. In the end, WHERE threw away the row that LEFT JOIN had protected, and the query behaved like an INNER JOIN. When you move the condition to ON, you get 8 departments and Data Science shows 0. A condition in ON is part of the matching: it says "the students joined to this department are the students who study in this department and have a scholarship." If no matching student is found, the department row still stays.
The rule: a condition that decides which rows of the right table will match goes in ON; a condition that decides which rows are thrown out of the result goes in WHERE. If you want to filter the rows of the left table (for example, only the departments in the Faculty of Engineering), that condition can stay in WHERE, because the left table's columns never turn into NULL. The WHERE k.id IS NULL in the pattern for finding what is missing is in WHERE on purpose: there, the goal is exactly to throw away the matches.
The tables do not decide which join you write; the question does. Before you start a query, ask yourself one thing: should the missing rows also be visible? If the answer is no, INNER JOIN is enough. If the answer is yes, you write the table you want to see in full in FROM and use LEFT JOIN. If only the missing rows are wanted, you add the IS NULL filter to the LEFT JOIN. If you want the missing rows from both sides, you need FULL JOIN.
There is one more subtlety. For the question "department names of the students", writing LEFT JOIN is not wrong, but it changes nothing: student.department_id cannot be left empty, and every student has a department that exists, so no student would drop out. Both queries give 120 rows. The same cannot be said for advisors: advisor_id is empty for 8 students, so INNER and LEFT give different results in a list of students and advisors. When you choose the type, look at the data too: is there a row on the right side that might have no match?
Choose the tool each business question needs.
For each row, pick its match from the list, then check.
A RIGHT JOIN B gives the same result as B LEFT JOIN A; the order of the columns is whatever you wrote in SELECT. So in practice most people use only LEFT JOIN and write the table to show in full in FROM: when the query is read from left to right, it means "all departments, with their students if they have any." When you read a RIGHT JOIN that someone else wrote, the fastest way to understand it is to swap the two tables and turn it into a LEFT JOIN.
FULL JOIN is needed rarely, but it does one job very well: comparing two lists and showing the missing items on both sides together. To keep only the unmatched rows from the 34-row result in section 1, you check the primary keys of both sides.
Example 4 (case): Unmatched rows from both sides with FULL JOIN
SELECT d.code, b.name AS department FROM course d FULL JOIN department b ON b.id = d.department_id WHERE d.id IS NULL OR b.id IS NULL;
| code | department |
|---|---|
| GEN101 | NULL |
| GEN102 | NULL |
| GEN103 | NULL |
| GEN104 | NULL |
| NULL | Data Science and Analytics |
(5 rows)
The first four rows are the shared courses with no department (b.id is NULL), and the last row is the department with no courses (d.id is NULL). For someone who maintains the catalog, these five rows are the to-do list.
The same way of thinking works in every database. Go back to the small online ordering app from lesson 15: it has 4 customers and 5 orders. Elena signed up but has not placed an order yet; order 104 is a guest order placed without signing up, so its customer_id is empty. Maya has two orders.
customer
| id | name |
|---|---|
| 1 | Maya |
| 2 | Noah |
| 3 | Marco |
| 4 | Elena |
orders
| id | customer_id | amount |
|---|---|---|
| 101 | 1 | 22.50 |
| 102 | 3 | 6.00 |
| 103 | 1 | 4.00 |
| 104 | NULL | 15.00 |
| 105 | 2 | 49.50 |
In lesson 15, orders JOIN customer returned 4 rows: both Elena and the guest order had dropped out. Now the café wants to send a "welcome" discount to customers who have never placed an order, so the customer who dropped out is exactly the person we are looking for. First, let's join with customers on the left and look at the result.
customer is on the left and orders is on the right. How many rows does this query return?
SELECT m.name, s.id AS order_id, s.amount FROM customer m LEFT JOIN orders s ON s.customer_id = m.id;
The result really is 5 rows: Maya 101, Maya 103, Noah 105, Marco 102, and an Elena row with empty order columns. Now let's apply the pattern and keep only Elena.
Example 5 (outside the case): Who gets the welcome discount?
SELECT m.id, m.name FROM customer m LEFT JOIN orders s ON s.customer_id = m.id WHERE s.id IS NULL;
| id | name |
|---|---|
| 4 | Elena |
(1 row)
If you had written the tables the other way around (orders s LEFT JOIN customer m ... WHERE m.id IS NULL), you would still get one row, but this time it would be order 104, the $15.00 guest order: "orders that have no customer." The count is the same, but the question is completely different. The table on the left decides which question the query answers.
The pattern in its counting form: write the courses on the left, join the sections on the right, and count the right table's primary key. The six courses offered the fewest times:
SELECT d.code, d.name, COUNT(a.id) AS times_offered FROM course d LEFT JOIN course_offering a ON a.course_id = d.id GROUP BY d.id, d.code, d.name ORDER BY times_offered, d.code LIMIT 6;
| code | name | times_offered |
|---|---|---|
| NMC203 | Social Media Analytics | 0 |
| BUS102 | Accounting I | 1 |
| BUS204 | Principles of Marketing | 1 |
| CPR102 | Algorithms and Programming II | 1 |
| CPR104 |
Writing the right table's condition in WHERE and breaking the LEFT JOIN. Suppose you want the number of scholarship students per department like this:
SELECT b.name, COUNT(o.id) AS scholarship FROM department b LEFT JOIN student o ON o.department_id = b.id WHERE o.has_scholarship GROUP BY b.name ORDER BY scholarship, b.name;
| name | scholarship |
|---|---|
| New Media and Communication | 1 |
| Industrial Engineering | 2 |
| Business Administration | 4 |
| Computer Programming | 4 |
| Management Information Systems | 5 |
| Psychology | 5 |
| Software Engineering |
LEFT JOIN ... WHERE right.id IS NULL; look for the NULL in the right table's primary key. When you count, use COUNT(right.id), not COUNT(*), or an empty group shows as 1.Next lesson: So far you have always joined two tables; next you will join three or four tables in one path, and join a table to itself.
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.
| 1 |
| IND202 | Operations Research II | 1 |
(6 rows)
With an INNER JOIN, NMC203 would not be in the list at all, and the "least offered course" would look like a course that was offered once.
These two queries return the same 20 rows; the second one is easier to read.
SELECT b.name AS department, u.last_name FROM instructor u RIGHT JOIN department b ON u.department_id = b.id; SELECT b.name AS department, u.last_name FROM department b LEFT JOIN instructor u ON u.department_id = b.id;
Result: both give 20 rows. Every department has at least one instructor, so there is no unmatched department here; the row count equals the number of instructors.
In the Earbud music app database (earbud.sql), which you will use in the last exercise at the end of the lesson, list all artists with their song counts:
SELECT s.name, COUNT(sa.id) AS songs FROM artist s LEFT JOIN song sa ON sa.artist_id = s.id GROUP BY s.id, s.name ORDER BY songs;
| name | songs |
|---|---|
| Quantum Cat | 0 |
| Purple Tortoise | 1 |
| Misty Valley | 2 |
| Neon Heron | 3 |
| Prairie Strings | 4 |
| Asphalt Verse | 5 |
| Salt Pier | 7 |
| Broken Compass | 8 |
(8 rows)
In lesson 14, grouping the song table gave 7 groups; Quantum Cat, which has no songs, did not appear there. LEFT JOIN brings it back with 0.
(7 rows)
The query gives no error, but only 7 of the 8 departments come back; Data Science, which has no scholarship students, disappears. LEFT JOIN had produced a row with NULLs for it, and WHERE threw that row away. Move the condition to ON: LEFT JOIN student o ON o.department_id = b.id AND o.has_scholarship, and delete the WHERE line. Now all eight departments come back, and Data Science shows 0. If a LEFT JOIN returns fewer rows than you expected, the first place to look is the right table's columns in WHERE.