Skip to content
RED SAGSkills

Top Two Products per Category

Using products and order_items, find the two best-selling products in each category by total units sold (sum of quantity). If two products tie on units, the one whose name comes first alphabetically wins. Products with no sales are not considered. A category with only one selling product returns one row. Product names are unique.

Return columns category, name, units_sold. Order by category ascending, units_sold descending, then name ascending.

Schema

CREATE TABLE products (
  product_id INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  category TEXT NOT NULL
);
CREATE TABLE order_items (
  order_id INTEGER NOT NULL,
  product_id INTEGER NOT NULL,
  quantity INTEGER NOT NULL
);

Sample data

products

product_idnamecategory
1Desk LampHome
2Throw PillowHome
3Wall ClockHome
4USB-C CableElectronics
5EarbudsElectronics
6Power BankElectronics

order_items

order_idproduct_idquantity
112
143
225
251
331
342
464
411
552
Hint 1

First total the units per product, then rank the products inside each category.

Hint 2

ROW_NUMBER, unlike RANK, never gives two rows the same number, so "top 2" means exactly two rows.

Good practice for: Data Analyst, Business Analyst, Product Manager, Data Engineer

SQL (SQLite)

Run checks your query on the sample data (Ctrl + '). Submit also checks hidden databases.