The RIGHT JOIN keyword returns all records from the right table (table2), and the matching records from the left table (table1). The result is NULL from the left side if there is no match.
!RIGHT JOIN Diagram
RIGHT JOIN SyntaxSELECT column_name(s) FROM table1 RIGHT JOIN table2 ON table1.column_name = table2.column_name;
Note: In some databases,
RIGHT JOINis calledRIGHT OUTER JOIN. They are the same.
Customers Table:
| CustomerID | CustomerName |
|---|---|
| 1 | Alfreds Futterkiste |
| 2 | Ana Trujillo Emparedados |
| 3 | Antonio Moreno Taquería |
Orders Table:
| OrderID | CustomerID |
|---|---|
| 10308 | 2 |
| 10309 | 99 |
| 10310 | 1 |
RIGHT JOIN ExampleThe following SQL statement will return all orders, and the customer name for each order if a matching customer exists.
SELECT Orders.OrderID, Customers.CustomerName FROM Customers RIGHT JOIN Orders ON Customers.CustomerID = Orders.CustomerID ORDER BY Orders.OrderID;
The result set would look like this:
| OrderID | CustomerName |
|---|---|
| 10308 | Ana Trujillo Emparedados |
| 10309 | NULL |
| 10310 | Alfreds Futterkiste |
Notice that OrderID 10309, which has no matching customer, is still included in the result set. The CustomerName for this order is NULL.