Skip to content
Quantoros

Using orderitems and products: return each categorys top 3 products by total quantity sold: category, productname,…

SQLLevel: IntermediateRanking and Top-N

Using order_items and products: return each categorys top 3 products by total quantity sold: category, product_name, total_qty. Break ties alphabetically by product name.

Table definitions (from the source exercise):

CREATE TABLE products(product_id INTEGER PRIMARY KEY, product_name TEXT, category TEXT, price REAL);
CREATE TABLE order_items(item_id INTEGER PRIMARY KEY, order_id INTEGER, product_id INTEGER, quantity INTEGER);
Hints
  • Define one output row and the source-table keys.
  • Check duplicates, NULLs and the order of filtering and aggregation.

Answer

Approach: Aggregate per product in a CTE, ROW_NUMBER partitioned by category, keep rn <= 3.

WITH pq AS (
  SELECT p.category, p.product_name, SUM(oi.quantity) AS total_qty
  FROM order_items oi
  JOIN products p ON p.product_id = oi.product_id
  GROUP BY p.category, p.product_name
)
SELECT category, product_name, total_qty
FROM (
  SELECT pq.*, ROW_NUMBER() OVER (PARTITION BY category
                                  ORDER BY total_qty DESC, product_name) AS rn
  FROM pq
) x
WHERE rn <= 3;

The source uses SQLite with a MySQL compatibility layer. Date and string functions are dialect dependent; the query is preserved as published.

Source and licence: SQL Practice Lab — Ebrahim Sharifi · MIT

Related questions