sqlstreak

SQL how-to

How to get the top N rows per group in SQL

Updated · Tested on PostgreSQL 18.6 and SQLite 3.54.1 (results generated , re-checked on every release)

Short answer

Number the rows inside each group with ROW_NUMBER() OVER (PARTITION BY species ORDER BY weight_kg DESC) in a subquery or CTE, then keep the rows numbered N or less. Use RANK() instead when tied rows should all make the cut.

The task: Get the top N rows within each group, for example the two heaviest pets of each species.

The two heaviest pets of each species

SELECT species, name, weight_kg
FROM (SELECT species, name, weight_kg,
        ROW_NUMBER() OVER (PARTITION BY species ORDER BY weight_kg DESC) AS rn
      FROM pets) ranked
WHERE rn <= 2
ORDER BY species, rn;

Result (PostgreSQL and SQLite, identical): 8 rows

speciesnameweight_kg
birdZiggy0.1
birdKiwi0.1
catSocks7.4
catPumpkin5.2
dogBruno30.1
dogMaple27.3
rabbitJuniper3.4
rabbitClover2.1

Try it: PostgreSQL playground · SQLite playground

How it works

  1. 1
    PARTITION BY species

    Restart the numbering for each species.

  2. 2
    ORDER BY weight_kg DESC

    Heaviest first, so number 1 is the heaviest of its species.

  3. 3
    FROM (…) ranked

    The numbering must exist before you can filter on it, so it goes in a subquery (or CTE).

  4. 4
    WHERE rn <= 2

    The top two of each group.

More examples

The same with a CTE

Reads top to bottom: rank first, then filter.

WITH ranked AS (
  SELECT species, name, weight_kg,
    ROW_NUMBER() OVER (PARTITION BY species ORDER BY weight_kg DESC) AS rn
  FROM pets
)
SELECT species, name, weight_kg
FROM ranked
WHERE rn <= 2
ORDER BY species, rn;

Result (PostgreSQL and SQLite, identical): 8 rows

speciesnameweight_kg
birdZiggy0.1
birdKiwi0.1
catSocks7.4
catPumpkin5.2
dogBruno30.1
dogMaple27.3
rabbitJuniper3.4
rabbitClover2.1

Try it: PostgreSQL playground · SQLite playground

RANK keeps ties

The top customer per city by number of orders. Where two customers tie, RANK keeps both; ROW_NUMBER would keep one at random.

SELECT city, name, orders
FROM (SELECT c.city, c.name, COUNT(o.id) AS orders,
        RANK() OVER (PARTITION BY c.city ORDER BY COUNT(o.id) DESC) AS r
      FROM customers c
      JOIN orders o ON o.customer_id = c.id
      GROUP BY c.id, c.city, c.name) ranked
WHERE r = 1
ORDER BY city, name;

Result (PostgreSQL and SQLite, identical): 5 rows

citynameorders
AustinMaya Ortiz4
BostonSam Okafor2
BostonTomás Herrera2
ChicagoMarcus Bell2
DenverJonah Reed3

Try it: PostgreSQL playground · SQLite playground

Variations

Bottom N instead

Flip the order: ORDER BY weight_kg ASC gives the lightest.

Top N overall, not per group

No window needed: ORDER BY weight_kg DESC LIMIT 2.

Common mistakes

  • GROUP BY species with MAX(weight_kg): you get the top weight, but not which pet it belongs to.

  • Filtering WHERE ROW_NUMBER() … <= 2 directly: window functions aren't allowed in WHERE.

  • Expecting ROW_NUMBER to keep ties: it never does. Use RANK or DENSE_RANK.

PostgreSQL and SQLite

Everything on this page works the same in PostgreSQL and SQLite: each example above was run on both, and the results match.

Official documentation

Go deeper

Make it stick in five minutes a day

“Ranking with OVER” teaches this step by step on a real database, with instant feedback. Part of sqlstreak Pro; the first lessons are free.

Start free