Join three tables
Question
For every order item, show the order id, the customer's name, the product's name and the quantity.
customersid, name, country, joined_on
productsid, name, category, price
ordersid, customer_id, ordered_on, status
order_itemsorder_id, product_id, quantity
Your query
Ctrl+Enter to run
Result
Expected result
| order_id | customer | product | quantity |
|---|---|---|---|
| 1 | Emma Clark | Keyboard | 1 |
| 1 | Emma Clark | Mouse | 1 |
| 2 | Ravi Kumar | Monitor | 2 |
| 3 | Emma Clark | USB-C hub | 1 |
| 4 | Julia Weber | Laptop stand | 1 |
| 4 | Julia Weber | Webcam | 1 |
| 5 | Kenji Sato | Monitor | 1 |
| 6 | Ana Lima | Keyboard | 2 |
| 6 | Ana Lima | Mouse | 2 |
| 7 | Ravi Kumar | Webcam | 1 |
Hint
Start from order_items, then join orders, customers and products one after another.
Show the solution
solution.sql
Run this code
SELECT o.id AS order_id, c.name AS customer, p.name AS product, i.quantity
FROM order_items i
JOIN orders o ON o.id = i.order_id
JOIN customers c ON c.id = o.customer_id
JOIN products p ON p.id = i.product_id;
Why it works
Each JOIN adds one table, linked through its key. order_items connects to orders and products, and orders connects to customers.
Common mistake
Joining customers on c.id = i.order_id (the wrong column) still runs, but pairs customers with random orders. Check that each ON links a foreign key to the key it points to.