SQL Practice Problem #026

Find the top product in each category

Return the highest priced product for each category.

Problem

Task

Return the highest priced product for each category.

Schema

Table Schema

products(id, title, category, price)

Input

Sample Data

idtitlecategoryprice
1KeyboardAccessories49.99
2USB HubAccessories59
3MonitorDisplays219
4Portable DisplayDisplays180

Output

Expected Output

categorytitleprice
AccessoriesUSB Hub59
DisplaysMonitor219

Answer

Check Your Solution

Show Answer and Explanation

Correct Answer

WITH ranked_products AS (
  SELECT category, title, price,
    ROW_NUMBER() OVER (
      PARTITION BY category
      ORDER BY price DESC
    ) AS price_rank
  FROM products
)
SELECT category, title, price
FROM ranked_products
WHERE price_rank = 1
ORDER BY category;

Explanation

The CTE ranks products inside each category. The outer query keeps rank 1, which is the highest priced product in each category. ORDER BY category makes the final result predictable.

Common Mistakes

  • Using a single LIMIT 1, which returns only one product overall.
  • Grouping by category and selecting title without defining which title to keep.
  • Forgetting PARTITION BY category in the window function.

Concepts

Related Concepts

Window Functions CTE Top N per Group ROW_NUMBER Top N

Next practice

Related Problems