← Back to Chapters

MySQL RIGHT JOIN

? MySQL RIGHT JOIN

? Quick Overview

The RIGHT JOIN (aka RIGHT OUTER JOIN) returns all records from the right table and the matching records from the left table. When there is no match, columns from the left table are NULL.

? Key Concepts

  • Right table priority — all rows from the right table are preserved.
  • Nulls for non-matches — non-matching left-table columns become NULL.
  • Equivalent to LEFT JOIN by swapping tables — a RIGHT JOIN can be rewritten as LEFT JOIN by switching table order.
  • Useful when you need to ensure every entity from the right dataset appears in the result (e.g., all orders even when customer info is missing).

? Syntax / Theory

? View Code Example
// Syntax for RIGHT JOIN: keep all rows from table2 (right table)
SELECT columns
FROM table1
RIGHT JOIN table2
ON table1.common_column = table2.common_column;

? Code Example(s)

? View Code Example
// Get all customers and their orders; 
include orders even if customer info is missing
SELECT customers.customer_name, orders.order_id
FROM customers
RIGHT JOIN orders
ON customers.customer_id = orders.customer_id;
? View Code Example
// Get all products and their quantities from orders; 
include products that may have no orders
SELECT products.product_name, orders.quantity
FROM products
RIGHT JOIN orders
ON products.product_id = orders.product_id;

? Live Output / Explanation

What to expect

  • If orders has rows with no matching customers.customer_id, those rows still appear; customer_name will be NULL.
  • The result set size is at least the size of the right table (it may be larger if the join produces duplicates).
  • To see only matching rows (no NULLs), use INNER JOIN instead.

✅ Tips & Best Practices

  • Prefer LEFT JOIN when your mental model considers the left table primary — you can swap tables instead of using RIGHT JOIN.
  • Ensure join columns are indexed for performance on large tables.
  • Be explicit with qualified column names to avoid ambiguity when tables share column names.
  • Use COALESCE() to replace NULL values in the result with a default.

? Try It Yourself

  • Write a query to list all orders and the corresponding customer names, including orders whose customer row is missing.
  • Use RIGHT JOIN to get all products and their order quantities; handle NULL with COALESCE().
  • Rewrite a RIGHT JOIN query as a LEFT JOIN by swapping table positions and confirm identical results.