SQL Dojo
Pattern

Top N per group (with ties)

The N best rows of each group, such as the three priciest products per category, and how ROW_NUMBER, RANK and DENSE_RANK handle ties.

You need the first N rows of each group: the three priciest products of each category, the two best sellers of each month. Number the rows inside each group with a window function, then keep the first N.

SELECT category_id, name, unit_price
FROM (
  SELECT category_id, name, unit_price,
         RANK() OVER (PARTITION BY category_id ORDER BY unit_price DESC) AS rnk
  FROM products
) ranked
WHERE rnk <= 3
ORDER BY category_id, rnk;

The function decides what happens to ties. ROW_NUMBER gives 1, 2, 3, 4 and always returns exactly N rows; RANK gives 1, 2, 2, 4 and keeps every row tied at the cut; DENSE_RANK gives 1, 2, 2, 3: the rows at the N highest values.

The trap. ROW_NUMBER on an ORDER BY with ties picks among the tied rows arbitrarily: a product at the same price as the third one disappears, and not always the same one. Take RANK or DENSE_RANK when ties should stay, or add a unique tie-breaker (ORDER BY unit_price DESC, product_id) when you need exactly N rows.

On your warehouse. Snowflake, BigQuery, Databricks and DuckDB skip the subquery: QUALIFY RANK() OVER (…) <= 3. Postgres has no QUALIFY: keep the subquery there, or a LATERAL subquery with ORDER BY … LIMIT 3 per category.

SELECT category_id, name, unit_price,
       ROW_NUMBER() OVER (PARTITION BY category_id ORDER BY unit_price DESC, product_id) AS row_num,
       RANK()       OVER (PARTITION BY category_id ORDER BY unit_price DESC) AS rnk,
       DENSE_RANK() OVER (PARTITION BY category_id ORDER BY unit_price DESC) AS dense_rnk
FROM products
WHERE category_id IN (4, 15)
QUALIFY dense_rnk <= 3
ORDER BY category_id, unit_price DESC, product_id;
category_idnameunit_pricerow_numrnkdense_rnk
4Ethiopia Moka 1 kg31.90111
4Colombia Huila 1 kg27.90222
4Peru Organic 1 kg27.90322
4House Espresso 1 kg26.50443
15Chemex 6 cups52.00111
15AeroPress39.00222
15Filter carafe 600 ml34.00333
15Moka pot 6 cups34.00433
Try it in Randori