BBampaa

Lessons › SQL › Chapter 5: Joins, subqueries and CTEs

SQL lesson

Multi-table joins across three or more tables

Each JOIN adds one more table, matched on a column they share.

Try this lesson free →
About 5–10 minutes · no sign-up needed

Example

Joining three tables in one query

SELECT orders.order_id, customers.full_name, products.brand
FROM orders
JOIN customers ON orders.customer_id = customers.customer_id
JOIN products ON orders.product_id = products.product_id

Result:

order_idfull_namebrand
O2001Alice ChenNovaTech
O2002Bob TanakaUrbanThreads
O2004Alice ChenGlowUp

Step by step

  1. Written first. It has a customer_id and a product_id, so it links the other two.
    SELECT *
    FROM orders
  2. JOIN on its own keeps only matching rows. Each order gets its customer.
    SELECT *
    FROM orders
    JOIN customers ON orders.customer_id = customers.customer_id
  3. Add one more JOIN for each extra table, each with its own matching column.
    SELECT *
    FROM orders
    JOIN customers ON orders.customer_id = customers.customer_id
    JOIN products ON orders.product_id = products.product_id;

Practice

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

1. Using orders, customers and returns, show every column. Join them in that order.
SELECT * FROM orders JOIN customers ON orders.customer_id = customers.customer_id JOIN returns ON orders.order_id = returns.order_id
2. Using orders, customers and returns, show order_id, full_name and refund_amount. Join them in that order.
SELECT o.order_id, c.full_name, r.refund_amount FROM orders o JOIN customers c ON o.customer_id = c.customer_id JOIN returns r ON o.order_id = r.order_id
3. Using orders, customers and shipments, show every column. Join them in that order.
SELECT * FROM orders JOIN customers ON orders.customer_id = customers.customer_id JOIN shipments ON orders.order_id = shipments.order_id
4. Using reviews, products and customers, show every column. Join them in that order.
SELECT * FROM reviews JOIN products ON reviews.product_id = products.product_id JOIN customers ON reviews.customer_id = customers.customer_id
5. Using cart, customers and products, show every column. Join them in that order.
SELECT * FROM cart JOIN customers ON cart.customer_id = customers.customer_id JOIN products ON cart.product_id = products.product_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