A RIGHT JOIN is the mirror image of a LEFT JOIN. It returns all rows from the right table, and the matching rows from the left table. When a row in the right table has no match in the left table, the left-side columns are filled with NULL. No row from the right table is ever excluded.
SELECT columns
FROM table_a AS a
RIGHT JOIN table_b AS b ON a.id = b.foreign_key;
RIGHT JOIN and RIGHT OUTER JOIN are identical in MySQL — the OUTER keyword is optional.
Get all orders, with customer details where available:
SELECT c.name, c.city, o.id AS order_id, o.amount
FROM customers AS c
RIGHT JOIN orders AS o ON c.id = o.customer_id;
| name | city | order_id | amount |
|---|---|---|---|
| Rahim Uddin | Dhaka | 1 | 2500.00 |
| Rahim Uddin | Dhaka | 2 | 1200.00 |
| Karim Ali | Sylhet | 3 | 4800.00 |
| NULL | NULL | 4 | 900.00 |
All 4 orders appear in the result. Order id=4 references customer_id=6 which does not exist — so the customer columns show NULL. Sara Begum and Nila Akter do not appear because they are in the left table and have no matching orders in the right table.
Just like LEFT JOIN can find customers without orders, a RIGHT JOIN can find orders that reference a non-existent customer:
-- Orders with no matching customer
SELECT o.id, o.amount, o.customer_id
FROM customers AS c
RIGHT JOIN orders AS o ON c.id = o.customer_id
WHERE c.id IS NULL;
| id | amount | customer_id |
|---|---|---|
| 4 | 900.00 | 6 |
A RIGHT JOIN can always be rewritten as a LEFT JOIN simply by swapping the table order. These two queries return identical results:
-- RIGHT JOIN
SELECT c.name, o.amount
FROM customers AS c
RIGHT JOIN orders AS o ON c.id = o.customer_id;
-- Equivalent LEFT JOIN (tables swapped)
SELECT c.name, o.amount
FROM orders AS o
LEFT JOIN customers AS c ON c.id = o.customer_id;
LEFT JOIN and reorder their tables accordingly, since it reads more naturally — "start with this table, and optionally bring in data from that one." RIGHT JOIN is less common but useful when you cannot change the table order in a more complex query.
RIGHT JOIN returns all rows from the right table plus matched rows from the left.NULL.RIGHT JOIN keyword.RIGHT JOIN can be rewritten as a LEFT JOIN by swapping the table positions.WHERE left_table.id IS NULL after a RIGHT JOIN to find orphaned records in the right table.