SQL Top N Per Group (ROW_NUMBER Pattern)

Get the top N rows in each category or customer using ROW_NUMBER() OVER (PARTITION BY …) — with a clear shop example.

products Milk $3 Cheese $8 RANK() still 2 rows Cheese · rank 1 Milk · rank 2
Unlike GROUP BY, window functions keep every row and add a calculated column.

Why LIMIT alone isn’t enough

ORDER BY price DESC LIMIT 3 gives the global top 3. For “top 3 products per category,” you need a ranking that restarts in each group.

The standard pattern

WITH ranked AS (
  SELECT
    name, category, price,
    ROW_NUMBER() OVER (
      PARTITION BY category
      ORDER BY price DESC
    ) AS rn
  FROM products
)
SELECT name, category, price
FROM ranked
WHERE rn <= 3;

Swap ROW_NUMBER for RANK if ties should share a place.

Also used for “latest record per entity”

Same idea for “latest order per customer”: PARTITION BY customer_id ORDER BY order_date DESC, then keep rn = 1.

WITH ranked AS (
  SELECT order_id, customer_id, order_date,
    ROW_NUMBER() OVER (
      PARTITION BY customer_id
      ORDER BY order_date DESC
    ) AS rn
  FROM orders
)
SELECT order_id, customer_id, order_date
FROM ranked
WHERE rn = 1;

FAQ

How do I select the top N rows per group in SQL?

Compute ROW_NUMBER() OVER (PARTITION BY group_col ORDER BY metric DESC), then filter WHERE rn <= N in an outer query or CTE.

Try it yourself

The fastest way to lock this in is a short drill on the same Northstar Market tables.

Practice window PARTITION BY

Related guides