Lessons › SQL › Chapter 5: Joins, subqueries and CTEs
SQL lesson
RIGHT JOIN
A RIGHT JOIN is a LEFT JOIN the other way round. It keeps every row from the right table, no matter what. The first table you write (orders) is the left table. The second (customers) is the right table. Every customer stays. If a customer has no orders, their order columns are empty.
Try this lesson free →Example
Keeping All Customers with RIGHT JOIN
SELECT *
FROM orders
RIGHT JOIN customers ON orders.customer_id = customers.customer_id| order_id | customer_id | revenue | customer_id | full_name |
|---|---|---|---|---|
| O2001 | C101 | 129.99 | C101 | Alice Chen |
| O2002 | C102 | 54.5 | C102 | Bob Tanaka |
| NULL | NULL | NULL | C103 | Carol White |
Step by step
- It's written first, so SQL calls it the left table.
SELECT * FROM orders - The extra table. It's written second, so SQL calls it the right table. This time every customer stays. If a customer has no match, their order columns are empty.
SELECT * FROM orders RIGHT JOIN customers - Both tables have a customer_id column. SQL uses it to match each order to its customer. Writing orders. in front just means 'the customer_id in orders'.
SELECT * FROM orders RIGHT JOIN customers ON orders.customer_id = customers.customer_id;
Practice
1. Using orders and customers, show every column. Keep every customer, even ones with no orders.
SELECT * FROM orders RIGHT JOIN customers ON orders.customer_id = customers.customer_id2. Using orders and customers, show full_name, order_id and revenue. Keep every customer, even ones with no orders.
SELECT c.full_name, o.order_id, o.revenue FROM orders o RIGHT JOIN customers c ON o.customer_id = c.customer_id3. Using products and reviews, show every column. Keep every review, even ones with no matching product.
SELECT * FROM products RIGHT JOIN reviews ON products.product_id = reviews.product_id4. Using orders and shipments, show every column. Keep every shipment, even ones with no matching order.
SELECT * FROM orders RIGHT JOIN shipments ON orders.order_id = shipments.order_id5. Using suppliers and supplier_products, show every column. Keep every supplier product, even ones with no matching supplier.
SELECT * FROM suppliers RIGHT JOIN supplier_products ON suppliers.supplier_id = supplier_products.supplier_idLearn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.
Try this lesson free →