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 →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| order_id | full_name | brand |
|---|---|---|
| O2001 | Alice Chen | NovaTech |
| O2002 | Bob Tanaka | UrbanThreads |
| O2004 | Alice Chen | GlowUp |
Step by step
- Written first. It has a customer_id and a product_id, so it links the other two.
SELECT * FROM orders - 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 - 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
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_id2. 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_id3. 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_id4. 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_id5. 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_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 →