Medium SQL joins practice Shop database

Total quantity sold per product

Question

Show each product's name and the total quantity ordered across all orders, highest total first.

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

nametotal_quantity
Keyboard3
Monitor3
Mouse3
Webcam2
Laptop stand1
USB-C hub1

The row order matters for this question.

Hint

Join products to order_items, group by product, and SUM the quantity.

Show the solution
solution.sql Run this code
SELECT p.name, SUM(i.quantity) AS total_quantity
FROM products p
JOIN order_items i ON i.product_id = p.id
GROUP BY p.id, p.name
ORDER BY total_quantity DESC, p.name;

Why it works

The join gives one row per order item with the product name attached; GROUP BY then adds up the quantities per product. Ordering by name as a second key makes ties come out in a fixed order.

Common mistake

Grouping by name alone would merge two different products that happen to share a name. Group by the id (and the name you show).

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