skip to content

LEFT, RIGHT and FULL joins

keep the rows that didn't match, padded with NULLs. and the WHERE that turns them back into inner joins.

address
everything.joins.outer_joins
part
part 3, joins and subqueries
chapter
chapter 3 of 11
reading time
9 min

a LEFT JOIN returns every pair that matched, plus each left row that matched nothing, once, with NULLs in the right table's columns. RIGHT JOIN does the same for the right table, and FULL JOIN for both.

a WHERE on the right table runs after the padding and throws it away. put that condition in ON instead.

the picture

you know how you ask for every instructor with their courses, and the list comes back one instructor short? Sofia Petrova teaches nothing this year, so an inner join has nothing to pair her with, and she's just not there.

think of a class photo. everyone who showed up sits in their seat. a LEFT JOIN also keeps a seat for every kid who stayed home: an empty chair with their name card on it. the name card is the left row, the empty chair is the NULLs.

join =
data =
courses.instructor_id ↓ instructors.id →3 Lena Fischer6 Amara Diallo7 Oliver Grant8 Sofia Petrova
3 CS401✓···
NULL CS499····
7 HIST101··✓·
6 PHYS101·✓··
6 PHYS201·✓··
left join result
codeinstructor_ididname
CS40133Lena Fischer
HIST10177Oliver Grant
PHYS10166Amara Diallo
PHYS20166Amara Diallo
CS499nullnullnull
(5 rows)

the 4 matching pairs, plus 1 leftover row padded with NULLs (marked ref above): an outer join never loses a row from its outer side.

model of SQL join semantics · checked against postgres 18.6
five courses down the side, four instructors across the top. switch the join type: CS499 has no instructor, Sofia Petrova has no course. a leftover row comes back padded, from the left side with LEFT, the right side with RIGHT, both with FULL.

the figure uses five of the 12 courses and four of the 8 instructors, so the grid fits. the full tables tell the same story, which is what the rest of this chapter runs.

LEFT JOIN

every instructor, with their courses if they have any:

sqldb=school
SELECT i.name, c.code, c.title
FROM instructors AS i
LEFT JOIN courses AS c ON c.instructor_id = i.id
ORDER BY i.id, c.code;
output, from postgres 18.6
SELECT 12
nametextcodetexttitletext
Hannah OkoyeCS101Intro to Programming
Hannah OkoyeCS301Databases
Marco RossiCS201Data Structures
Marco RossiCS350Operating Systems
Lena FischerCS401Database Internals
Tomás OrtegaMATH101Calculus I
Tomás OrtegaMATH301Linear Algebra
Yuki TanakaMATH201Discrete Math
Amara DialloPHYS101Mechanics
Amara DialloPHYS201Electromagnetism
Oliver GrantHIST101History of Computing
Sofia Petrovanullnull
(12 rows)

12 rows: 11 matched pairs (Hannah Okoye teaches two courses, so she's in two rows), plus Sofia Petrova, once, with NULL for code and title. nobody stored those NULLs. they're the join's way of writing "no partner". (LEFT OUTER JOIN is the same thing. the OUTER is optional and almost nobody types it.)

"left" just means the table written before the keyword. that's the one that keeps all its rows. a LEFT JOIN can't return fewer rows than its left table, and it can return more: one row per match, and at least one per left row.

RIGHT and FULL

RIGHT JOIN keeps every row of the table written after the keyword. a RIGHT JOIN b is b LEFT JOIN a with the columns in a different order, so most people only ever write LEFT and put the table they care about first.

FULL JOIN keeps the leftovers from both sides. every course with its instructor, and every instructor with their course, in one list:

sqldb=school
SELECT c.code, i.name
FROM courses AS c
FULL JOIN instructors AS i ON i.id = c.instructor_id
ORDER BY c.code NULLS LAST, i.name;
output, from postgres 18.6
SELECT 13
codetextnametext
CS101Hannah Okoye
CS201Marco Rossi
CS301Hannah Okoye
CS350Marco Rossi
CS401Lena Fischer
CS499null
HIST101Oliver Grant
MATH101Tomás Ortega
MATH201Yuki Tanaka
MATH301Tomás Ortega
PHYS101Amara Diallo
PHYS201Amara Diallo
nullSofia Petrova
(13 rows)

13 rows: the 11 pairs, CS499 with no instructor (the senior thesis has nobody assigned yet), and Sofia Petrova with no course. FULL JOIN is the one you reach for when you're comparing two lists and want to see what's missing on either side.

counting what isn't there

padded rows are real rows, which matters the moment you count them:

sqldb=school
SELECT i.name, count(*) AS rows, count(c.code) AS courses
FROM instructors AS i
LEFT JOIN courses AS c ON c.instructor_id = i.id
GROUP BY i.id
ORDER BY i.id;
output, from postgres 18.6
SELECT 8
nametextrowsint8coursesint8
Hannah Okoye22
Marco Rossi22
Lena Fischer11
Tomás Ortega22
Yuki Tanaka11
Amara Diallo22
Oliver Grant11
Sofia Petrova10
(8 rows)

count(*) counts rows, and Sofia has one: the padded one. count(c.code) counts values that aren't NULL, and she has none. so to count matches through a LEFT JOIN, count a column from the right table, ideally its primary key. (aggregate functions has the three counts side by side.) sum has the opposite problem: over nothing but NULLs it's NULL, not 0, so wrap it in coalesce(sum(...), 0) when a zero is what you mean.

the WHERE that undoes a LEFT JOIN

now the classic. same LEFT JOIN, but only the 4-credit courses:

predict the output
sql
SELECT i.name, c.code, c.credits
FROM instructors AS i
LEFT JOIN courses AS c ON c.instructor_id = i.id
WHERE c.credits >= 4;

step through it. the stepper's tables are the real intermediate results, captured from the same postgres the page runs:

query.sqlstep 1: FROM
  1. 1SELECT i.name, c.code, c.credits
  2. 2FROM instructors AS i
  3. 3LEFT JOIN courses AS c ON c.instructor_id = i.id
  4. 4WHERE c.credits >= 4
  5. 5ORDER BY i.id, c.code;
the table after FROM
nametextcodetextcreditsint2
Hannah OkoyeCS1014
Hannah OkoyeCS3014
Marco RossiCS2014
Marco RossiCS3504
Lena FischerCS4014
Tomás OrtegaMATH1014
Tomás OrtegaMATH3013
Yuki TanakaMATH2013
Amara DialloPHYS1014
Amara DialloPHYS2014
Oliver GrantHIST1013
Sofia Petrovanullnull
(12 rows)

the LEFT JOIN keeps all 8 instructors: 11 matched pairs, plus Sofia Petrova, who teaches nothing, padded with NULLs. 12 rows.

the query that produced this table
SELECT i.name, c.code, c.credits FROM instructors AS i LEFT JOIN courses AS c ON c.instructor_id = i.id ORDER BY i.id, c.code
clause 1/3
real output, postgres 18.6 (PGlite 0.5.12) · outer
FROM builds the LEFT JOIN, padded row and all. then WHERE strikes four rows, Sofia's padded one among them: NULL >= 4 isn't true.

the fix is to move the condition into ON. ON decides which pairs count as a match, before the padding. a course with 3 credits then simply isn't a match, and an instructor with no 4-credit course gets the padded row instead of disappearing:

don'tin WHERE: 8 rows, 5 instructors
sqldb=school
SELECT i.name, c.code, c.credits
FROM instructors AS i
LEFT JOIN courses AS c ON c.instructor_id = i.id
WHERE c.credits >= 4
ORDER BY i.id, c.code;
output, from postgres 18.6
SELECT 8
nametextcodetextcreditsint2
Hannah OkoyeCS1014
Hannah OkoyeCS3014
Marco RossiCS2014
Marco RossiCS3504
Lena FischerCS4014
Tomás OrtegaMATH1014
Amara DialloPHYS1014
Amara DialloPHYS2014
(8 rows)
doin ON: 11 rows, all 8
sqldb=school
SELECT i.name, c.code, c.credits
FROM instructors AS i
LEFT JOIN courses AS c ON c.instructor_id = i.id AND c.credits >= 4
ORDER BY i.id, c.code;
output, from postgres 18.6
SELECT 11
nametextcodetextcreditsint2
Hannah OkoyeCS1014
Hannah OkoyeCS3014
Marco RossiCS2014
Marco RossiCS3504
Lena FischerCS4014
Tomás OrtegaMATH1014
Yuki Tanakanullnull
Amara DialloPHYS1014
Amara DialloPHYS2014
Oliver Grantnullnull
Sofia Petrovanullnull
(11 rows)

postgres can tell that the WHERE undid the outer join. compare the two plans: the second one doesn't do an outer join at all.

sqldb=school
EXPLAIN (COSTS OFF)
SELECT i.name, c.code FROM instructors AS i
LEFT JOIN courses AS c ON c.instructor_id = i.id;
 
EXPLAIN (COSTS OFF)
SELECT i.name, c.code FROM instructors AS i
LEFT JOIN courses AS c ON c.instructor_id = i.id
WHERE c.credits >= 4;
output, from postgres 18.6
#1 · EXPLAIN
Hash Right Join Hash Cond: (c.instructor_id = i.id) -> Seq Scan on courses c -> Hash -> Seq Scan on instructors i
#2 · EXPLAIN
Hash Join Hash Cond: (c.instructor_id = i.id) -> Seq Scan on courses c Filter: (credits >= 4) -> Hash -> Seq Scan on instructors i

the first is your LEFT JOIN (Hash Right Join is the same join with its two inputs swapped: the planner chose to hash instructors). the second is a plain Hash Join. c.credits >= 4 can never be true for a padded row, so postgres drops the padding step it would only throw away. it didn't change your answer. it just shows you what your query already meant.

the rule of thumb: in a LEFT JOIN, conditions on the right table go in ON, conditions on the left table go in WHERE. a condition on the left table in ON doesn't filter anything, by the way: a left row that fails it just comes back padded.

there's one WHERE on the right table that's on purpose: WHERE c.code IS NULL. it keeps only the padded rows, which is "instructors who teach nothing". that's an anti join, and EXISTS, semi joins and anti joins has the cleaner way to write it.

a LEFT JOIN, then an inner one

the other way to lose your padded rows: join something else after them with a plain JOIN. "how many students does each instructor teach?" goes instructors → courses → enrollments:

then =
query.sql
  1. 1SELECT i.name, count(e.student_id) AS students
  2. 2FROM instructors AS i
  3. 3LEFT JOIN courses AS c ON c.instructor_id = i.id
  4. 4JOIN enrollments AS e ON e.course_code = c.code
  5. 5GROUP BY i.id
  6. 6ORDER BY i.id;
the result for JOIN
nametextstudentsint8
Hannah Okoye28
Marco Rossi36
Lena Fischer13
Tomás Ortega27
Yuki Tanaka16
Amara Diallo33
Oliver Grant11
(7 rows)

LEFT JOIN, then an inner JOIN: Sofia's padded row has no course code to match an enrollment, so the inner join drops her. 7 instructors.

real output, postgres 18.6 (PGlite 0.5.12) · outer
switch the second join. a plain JOIN needs a course code to match an enrollment, and Sofia's padded row has NULL there, so she drops out. a second LEFT JOIN keeps her, with 0 students.

the padded row reaches the second join like any other row, with NULL in c.code, and an inner join on e.course_code = c.code has nothing to match it with. once a table hangs off an outer join, every join after it on that path usually has to be outer too. (or nest them, LEFT JOIN (courses AS c JOIN enrollments AS e ON e.course_code = c.code) ON c.instructor_id = i.id, which says "instructors, and their courses that have students".)

this is also why outer joins can't be reordered as freely as inner joins: (a LEFT JOIN b) JOIN c and a LEFT JOIN (b JOIN c) are different questions with different answers.

keylines

  • LEFT JOIN: every matched pair, plus each unmatched left row once, padded with NULLs.
  • RIGHT is LEFT with the tables swapped. FULL keeps leftovers from both sides.
  • count a right-table column, not *, to count matches through a LEFT JOIN.
  • conditions on the right table go in ON. in WHERE they drop the padded rows.
  • after an outer join, a plain JOIN on the padded side undoes it.