RIGHT JOIN
- SQL course
- Intermediate
- Lesson 8/115
- 4 min
Keep all rows from the right table.
RIGHT JOIN
RIGHT JOIN keeps every row from the right table. Unmatched left columns arrive as NULL.
SELECT c.name, o.id
FROM orders o
RIGHT JOIN customers c ON o.customer_id = c.id;This query customers without orders also appear.
c.name, o.id is selected from orders o. customers c is joined on o.customer_id = c.id, keeping every row of the right table.
RIGHT JOIN — details
RIGHT JOIN is the mirror of LEFT JOIN. Swapping table order and using LEFT JOIN gives the same result.
For example, orders RIGHT JOIN customers and customers LEFT JOIN orders produce the same rows; only the order of writing differs.
Practice RIGHT JOIN
Join orders with customers using RIGHT JOIN.
Starter code
-- right join
SELECT c.name, o.id
FROM orders oSample solution
SELECT c.name, o.id
FROM orders o
RIGHT JOIN customers c ON o.customer_id = c.id;Expected output
name id Ayşe 1 Fatma NULL
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Add RIGHT JOIN
SELECT c.name, o.id
FROM orders o
____ customers c ON o.customer_id = c.id;
SELECT c.name, o.id
FROM orders o
RIGHT JOIN customers c ON o.customer_id = c.id;
Explanation: RIGHT JOIN is the right answer.
2 What does RIGHT JOIN keep entirely?
- The left table
- None
- The right table Correct answer
- Only the matching rows
Explanation: RIGHT JOIN keeps all rows of the right table.
3 RIGHT JOIN: match the terms
| Term | Meaning |
|---|---|
RIGHT JOIN |
all right |
NULL |
no match |
LEFT JOIN |
all left |
ON |
condition |