HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

MySQL RIGHT JOIN

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.

customers
(matched)
orders
(all rows)

Syntax

SELECT columns
FROM table_a AS a
RIGHT JOIN table_b AS b ON a.id = b.foreign_key;
Note: RIGHT JOIN and RIGHT OUTER JOIN are identical in MySQL — the OUTER keyword is optional.

RIGHT JOIN Example

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;
namecityorder_idamount
Rahim UddinDhaka12500.00
Rahim UddinDhaka21200.00
Karim AliSylhet34800.00
NULLNULL4900.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.


Finding Orphaned Records

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;
idamountcustomer_id
4900.006

RIGHT JOIN vs LEFT JOIN

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;
In practice: Most developers prefer 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.

Key Points to Remember

  • RIGHT JOIN returns all rows from the right table plus matched rows from the left.
  • Unmatched left-side columns are filled with NULL.
  • The right table is the one written after the RIGHT JOIN keyword.
  • Any RIGHT JOIN can be rewritten as a LEFT JOIN by swapping the table positions.
  • Use WHERE left_table.id IS NULL after a RIGHT JOIN to find orphaned records in the right table.
What's next? The next lesson covers CROSS JOIN — which produces every possible combination of rows from two tables, with no matching condition required.