Lessons › SQL › Deep Dive: Advanced Joins & Subqueries
SQL lesson
RIGHT JOIN
RIGHT JOIN returns every row from the second (right-side) table, filling in matching data from the first table where it exists and leaving gaps where it doesn't.
Try this lesson free →Example
Keeping All Customers with RIGHT JOIN
SELECT c.customer_id, c.region, o.order_id, o.revenue
FROM orders o
RIGHT JOIN customers c
ON o.customer_id = c.customer_id| customer_id | region | order_id | revenue |
|---|---|---|---|
| C101 | Northeast | O2001 | 129.99 |
| C102 | Southeast | O2002 | 54.5 |
| C103 | Midwest | ||
| C104 | West | O2003 | 210.0 |
| C105 | Southwest |
Step by step
- After SELECT, list the column names you want, separated by commas.
SELECT c.customer_id, c.region, o.order_id, o.revenue - FROM tells SQL which table to pull the data from.
SELECT c.customer_id, c.region, o.order_id, o.revenue FROM orders o - RIGHT JOIN keeps every row from the right table, even when no match exists.
SELECT c.customer_id, c.region, o.order_id, o.revenue FROM orders o RIGHT JOIN customers c ON o.customer_id = c.customer_id;
Practice
1. Write a query that returns every row from customers and matching rows from orders on customer_id.
SELECT * FROM orders RIGHT JOIN customers ON orders.customer_id = customers.customer_id2. Right join orders to returns on order_id so every return record appears, even those with no matching order.
SELECT * FROM orders RIGHT JOIN returns ON orders.order_id = returns.order_id3. Look at the products and reviews tables. Find the column they share, then write a RIGHT JOIN so every review appears - even those with no matching product.
SELECT * FROM products RIGHT JOIN reviews ON products.product_id = reviews.product_id4. Examine the orders and shipments tables. Identify their shared column, then write a RIGHT JOIN so every shipment record appears - even those with no matching order.
SELECT * FROM orders RIGHT JOIN shipments ON orders.order_id = shipments.order_id5. Look at the suppliers and supplier_products tables. Find the column they have in common, then write a RIGHT JOIN so every product record appears - even those without a 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 →