LEFT, RIGHT & FULL Joins
Keep rows that have no partner with LEFT, RIGHT and FULL joins, and learn why ON and WHERE behave differently.
Outer joins keep the lonely rows
An outer join works like an inner join, then adds back the rows that found no partner and fills the missing side with NULL.
LEFT JOIN keeps every row of the table written before the word JOIN. RIGHT JOIN keeps every row of the table written after it. FULL JOIN keeps both. The word OUTER is optional, so LEFT JOIN and LEFT OUTER JOIN are the same.
Show everyone, even with nothing to show
Reports often need every customer, including the ones with no tickets yet. An inner join would hide them. An outer join lists them with NULL so you can see who is missing.
List every customer with their tickets
SELECT c.name, t.topic
FROM customers AS c
LEFT JOIN tickets AS t
ON c.id = t.customer_id;Asha has two tickets, Ben has one, and Chen, Dara and Eli have none, so they get NULL as the topic. That is 6 rows. A RIGHT JOIN here would keep the 4 tickets instead, and ticket 204, with no customer, would show NULL as the name. A FULL JOIN keeps both, giving 7 rows.
To find only the customers with no tickets, add WHERE t.id IS NULL. The padded rows are the only ones where the ticket id is NULL.
Switch the join and the test
Step through the four join types, then try the three extra tests. Compare WHERE with ON for the Login topic.
| idinteger | nametext |
|---|---|
| 1 | Asha |
| 2 | Ben |
| 3 | Chen |
| 4 | Dara |
| 5 | Eli |
| idinteger | customer_idinteger | topictext |
|---|---|---|
| 201 | 1 | Login |
| 202 | 1 | Billing |
| 203 | 2 | Login |
| 204 | NULL | Pricing |
| nametext | topictext |
|---|---|
| Asha | Login |
| Asha | Billing |
| Ben | Login |
| Chen | NULL |
| Dara | NULL |
| Eli | NULL |
LEFT keeps every customer. Customers with no ticket get NULL in the ticket columns.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- LEFT JOIN keeps every left row, RIGHT keeps every right row, FULL keeps both, and missing sides become NULL.
- LEFT JOIN plus WHERE right_key IS NULL finds the left rows that have no partner.
- A WHERE test on the right table removes the padded rows and turns a LEFT JOIN into an INNER JOIN.
- To filter the right table and still keep every left row, put the test in ON.
Done with this concept?
Mark it complete to track your progress. No login needed.