DataLane

15. Top two products per category

hardProNot started~14 minRankingWindow functionsJoins

Asked in screens shaped like: Amazon, Walmart, Target

Top-N per group is asked in almost every SQL screen. Return the two best-selling products inside each category by units, with a deterministic tie-break.

Requirements

  • Columns: category, product_id, name, units
  • units is SUM(qty) from order_items
  • At most two rows per category, ranked by units descending then product_id
  • Order by category, then units descending, then product_id

Expected output

category, product_id, name, units

Row order is graded, so ORDER BY matters here.

SQL editor

Loading SQL engine…

Ctrl/Cmd + Enter submits

Run your query to see the result set.

Pro problem

Hard problems unlock with Pro

Easy pads stay free. Medium and hard SQL and Python problems — editor, tests, hints, and solutions — open after you upgrade to Pro or coaching.

See plansPractice free easy problems
↑↓ navigate openesc close