SQL interview question: Best Seller per Category

Best Seller in Each Category

Merchandising wants to feature the top-selling product from each category on the homepage.

Find the product with the highest total quantity sold in each category.

Return category, product_name, and quantity_sold. If two products tie, keep the one with the lower product_id. Use ROW_NUMBER() OVER (PARTITION BY category ORDER BY quantity DESC).

Skills: RANK() or ROW_NUMBER() with PARTITION BY

Tables

order_items 19 rows
  • id integer PK
  • order_id integer → orders
  • product_id integer → products
  • quantity integer
idorder_idproduct_idquantity
1131
2211
3261
products 20 rows
  • product_id integer PK
  • product_name text
  • category text
  • price real
  • rating real
product_idproduct_namecategorypricerating
1MacBook ProElectronics1999.994.8
2iPad AirElectronics599.994.8
3AirPods ProElectronics249.994.7

Keep going