Difference between INNER JOIN, LEFT JOIN and RIGHT JOIN in MySQL
Start your free 7-days trial now!
INNER JOIN
MySQL's INNER JOIN
clause retrieves rows from both tables where there is a common matching column value.
Consider the very simplistic example where we have the following two tables:
Left table:
person_id | first_name |
---|---|
1 | Bob |
2 | Mary |
3 | Craig |
Right table:
person_id | last_name |
---|---|
1 | Builder |
2 | Poppins |
Table that results from joining the two tables using INNER JOIN
on the common column person_id
:
person_id | first_name | last_name |
---|---|---|
1 | Bob | Builder |
2 | Mary | Poppins |
As we have matching values of
person_id
in both the left and right table (both tables haveperson_id=1
andperson_id=2
), we retrieve thefirst_name
andlast_name
for each of these two people.For
person_id=3
this only exists in the left table and there is no match in the right table, henceperson_id=3
is not included in the table that results from theINNER JOIN
.
LEFT JOIN
MySQL's LEFT JOIN
clause returns all rows from the left table and records that match from the right table. NULL
will be used for records that have no matching record in the right table.
Consider again the very simplistic example where we have the following two tables:
Left table:
person_id | first_name |
---|---|
1 | Bob |
2 | Mary |
3 | Craig |
Right table:
person_id | last_name |
---|---|
1 | Builder |
2 | Poppins |
Table that results from joining the two tables using LEFT JOIN
on the common column person_id
:
person_id | first_name | last_name |
---|---|---|
1 | Bob | Builder |
2 | Mary | Poppins |
3 | Craig | NULL |
Here we retrieve all rows from the left table (i.e.
person_id=1
,person_id=2
,person_id=3
) regardless of whether they have a matching row in the right table.Next we retrieve the corresponding
last_name
for eachperson_id
from the right table.As
person_id=3
does not have a correspondinglast_name
in the right table, the value is populated asNULL
.
RIGHT JOIN
MySQL's RIGHT JOIN
clause returns all rows from the right table and matching records from the left table. NULL
will be used for records that have no matching record in the left table.
Consider again the very simplistic example where we have the following two tables:
Left table:
person_id | first_name |
---|---|
1 | Bob |
2 | Mary |
Right table:
person_id | last_name |
---|---|
1 | Builder |
2 | Poppins |
3 | Grey |
Table that results from joining the two tables using RIGHT JOIN
on the common column person_id
:
person_id | first_name | last_name |
---|---|---|
1 | Bob | Builder |
2 | Mary | Poppins |
3 | NULL | Grey |
Here we retrieve all rows from the right table (i.e.
person_id=1
,person_id=2
,person_id=3
) regardless of whether they have a matching row in the left table.Next we retrieve the corresponding
first_name
for eachperson_id
from the left table.As
person_id=3
does not have a correspondingfirst_name
in the left table, the value is populated asNULL
.