Medium SQL joins practice Shop database

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

Press Run to see your query's result, or Check answer to compare it with the expected result.

Expected result

order_idcustomerproductquantity
1Emma ClarkKeyboard1
1Emma ClarkMouse1
2Ravi KumarMonitor2
3Emma ClarkUSB-C hub1
4Julia WeberLaptop stand1
4Julia WeberWebcam1
5Kenji SatoMonitor1
6Ana LimaKeyboard2
6Ana LimaMouse2
7Ravi KumarWebcam1

Rows can come in any order. Column names do not have to match.

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.

Want to try the query on MySQL or PostgreSQL? Open it in the SQL Online Compiler or SQLite Online.