RIGHT JOIN
MySQL RIGHT JOIN
is similar to LEFT JOIN
,
except that the treatment of the joined tables is reversed.
Here is the syntax of the RIGHT JOIN
of two tables t1
and t2
:
In this syntax:
t1
is the left table andt2
is the right tablejoin_condition
specifies the rule for matching rows in both tables.
If the join_condition
uses the equal operator (=
) and the joined columns of both tables have the same name, you can use the USING
syntax:
So the following join conditions are equivalent:
and
How the RIGHT JOIN
works.
The RIGHT JOIN
starts selecting data from the right table (t2
). It matches each row from the right table with every row from the left table. If both rows cause the join condition to evaluate to TRUE
, it combines columns into a new row and includes this new row in the result set.
If a row from the right table does not have a matching row from the left table, it combines columns of rows from the right table with NULL
values for all columns of the right table into a new row and includes this row in the result set.
In other words, the RIGHT JOIN
returns all rows from the right table regardless of having matching rows from the left table or not.
It’s important to emphasize that RIGHT JOIN
and LEFT JOIN
clauses are functionally equivalent and they can replace each other as long as the table order is reversed.
Note that the RIGHT OUTER JOIN
is a synonym for RIGHT JOIN
.
MySQL RIGHT JOIN
examples
RIGHT JOIN
examplesWe’ll use the tables employees
and customers
from the sample database for the demonstration:
The column salesRepEmployeeNumber
in the table customers
links to the column employeeNumber
in the employees
table.
A sales representative, or an employee, may in charge of zero or more customers. And each customer is taken care of by zero or one sales representative.
If the value in the column salesRepEmployeeNumber
is NULL, it means the customer does not have any sales representative.
1) Simple MySQL RIGHT JOIN
example
RIGHT JOIN
exampleThis statement uses the RIGHT JOIN
clause join the table customers
with the table employees
.
In this example:
The
RIGHT JOIN
returns all rows from the tableemployees
whether rows in the tableemployees
have matching values in the columnsalesRepEmployeeNumber
of the tablecustomers
.If a row from the table
employees
has no matching row from the tablecustomers
, theRIGHT JOIN
usesNULL
for thecustomerNumber
column.
2) Using MySQL RIGHT JOIN
to find unmatching rows
RIGHT JOIN
to find unmatching rowsThe following statement uses the RIGHT JOIN
clause to find employees who do not in charge of any customers:
In this tutorial, you have learned how to use the MySQL RIGHT JOIN
to query data from two tables.
Last updated