BBampaa

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 →
About 5–10 minutes · no sign-up needed

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

Result:

customer_idregionorder_idrevenue
C101NortheastO2001129.99
C102SoutheastO200254.5
C103Midwest
C104WestO2003210.0
C105Southwest

Step by step

  1. After SELECT, list the column names you want, separated by commas.
    SELECT c.customer_id, c.region, o.order_id, o.revenue
  2. FROM tells SQL which table to pull the data from.
    SELECT c.customer_id, c.region, o.order_id, o.revenue
    FROM orders o
  3. 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

Try each one in your head first, then open the answer.

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_id
2. 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_id
3. 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_id
4. 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_id
5. 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_id

Learn 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 →
About 5–10 minutes · no sign-up needed