Learning navigation

Code with Animation

LEFT, RIGHT & FULL Joins

Keep rows that have no partner with LEFT, RIGHT and FULL joins, and learn why ON and WHERE behave differently.

SQL6 min readConcept 14 of 44

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.

SELECT c.name, t.topic
FROM customers AS c
LEFT JOIN tickets AS t ON c.id = t.customer_id
ORDER BY c.id NULLS LAST, t.id NULLS LAST;
customers AS c
idintegernametext
1Asha
2Ben
3Chen
4Dara
5Eli
tickets AS t
idintegercustomer_idintegertopictext
2011Login
2021Billing
2032Login
204NULLPricing
Result (6 rows)
nametexttopictext
AshaLogin
AshaBilling
BenLogin
ChenNULL
DaraNULL
EliNULL

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.

  1. 1`customers` has 5 rows. Asha has 2 tickets, Ben has 1, the other three have none. How many rows does `customers LEFT JOIN tickets` return?
  2. 2How do you list only the customers that have no tickets?
  3. 3A LEFT JOIN is followed by `WHERE t.topic = 'Login'`. What happens to customers with no tickets?

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.