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
Expected result
| name | total_quantity |
|---|---|
| Keyboard | 3 |
| Monitor | 3 |
| Mouse | 3 |
| Webcam | 2 |
| Laptop stand | 1 |
| USB-C hub | 1 |
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).