// SQL snippet

Top-N with ties per group

ROW_NUMBER throws away ties. RANK keeps every row that shares a leading value.

Main statement
All engines

The task

You want the two most expensive products in every category, but if three products tie at the top you want all three, not two of them picked at random.

The snippet

Runs unchanged on current versions of SQL Server, PostgreSQL, MySQL, SQLite and Oracle.

All engines
WITH ranked AS (
  SELECT name, category, price,
         RANK() OVER (PARTITION BY category
                      ORDER BY price DESC) AS rnk
  FROM products
)
SELECT name, category, price
FROM ranked
WHERE rnk <= 2
ORDER BY category, rnk;

So funktioniert es

RANK gives tied rows the same rank and skips the next number, so a three-way tie for first leaves every row at rank 1 and the next row at rank 4. The filter rnk <= 2 keeps everything tied inside the top two ranks. Swap in ROW_NUMBER when you need exactly N rows and can accept an arbitrary winner.

Variations

DENSE_RANK: no gaps after ties

WITH ranked AS (
  SELECT name, category, price,
         DENSE_RANK() OVER (PARTITION BY category
                            ORDER BY price DESC) AS rnk
  FROM products
)
SELECT name, category, price
FROM ranked
WHERE rnk <= 2
ORDER BY category, rnk;

Questions that come up

RANK, DENSE_RANK or ROW_NUMBER?

ROW_NUMBER is 1, 2, 3 with ties broken arbitrarily. RANK is 1, 1, 3 on ties. DENSE_RANK is 1, 1, 2. Use RANK to keep ties, DENSE_RANK when downstream logic wants consecutive levels.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.