BBampaa

Lessons › SQL › Chapter 5: Combining tables

SQL lesson

Multi-table joins across three or more tables

Joining more than two tables means chaining lookups together so each connection adds another layer of detail to the same result.

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

Example

Joining three tables in one query

SELECT orders.order_id, customers.name, products.name FROM orders JOIN customers ON orders.customer_id = customers.id JOIN products ON orders.product_id = products.id

Result:

order_idcustomer_nameproduct_name
1Alex ParkWireless Earbuds
2Jordan LeeCotton Tee
3Sam RiveraTravel Mug

Step by step

  1. After SELECT, list the column names you want, separated by commas.
    SELECT orders.order_id, customers.name, products.name
  2. FROM tells SQL which table to pull the data from.
    SELECT orders.order_id, customers.name, products.name
    FROM orders
  3. JOIN combines rows from two tables that share a key.
    SELECT orders.order_id, customers.name, products.name
    FROM orders
    JOIN customers ON orders.customer_id = customers.id

Practice

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

1. Join orders, customers and returns to show order_id, full_name and refund_amount for every returned order.
SELECT orders.order_id, customers.full_name, returns.refund_amount FROM orders JOIN customers ON orders.customer_id = customers.customer_id JOIN returns ON orders.order_id = returns.order_id
2. Join orders, order_details and products to show order_id, brand and quantity.
SELECT orders.order_id, products.brand, order_details.quantity FROM orders JOIN order_details ON orders.order_id = order_details.order_id JOIN products ON order_details.product_id = products.product_id
3. Join orders, customers and shipments to show order_id, full_name and carrier.
SELECT orders.order_id, customers.full_name, shipments.carrier FROM orders JOIN customers ON orders.customer_id = customers.customer_id JOIN shipments ON orders.order_id = shipments.order_id
4. Join reviews, products and customers to show brand, full_name and rating.
SELECT products.brand, customers.full_name, reviews.rating FROM reviews JOIN products ON reviews.product_id = products.product_id JOIN customers ON reviews.customer_id = customers.customer_id
5. Join cart, customers and products to show full_name, brand and quantity.
SELECT customers.full_name, products.brand, cart.quantity 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