Top N rows per group
Get the latest or highest N rows for each category using ROW_NUMBER in a subquery.
- SQL
- GreenSnippets
- MIT
SELECT *
FROM (
SELECT
p.*,
ROW_NUMBER() OVER (
PARTITION BY p.category_id
ORDER BY p.created_at DESC, p.id DESC
) AS rn
FROM products AS p
) AS ranked
WHERE rn <= 3
ORDER BY category_id, rn;Example / expected output
-- The 3 newest products in every categoryHow it works
ROW_NUMBER() OVER (PARTITION BY ... ORDER BY ...) numbers the rows inside each group, and an outer filter keeps the first N. Use RANK instead if ties should all be kept. For small N and an indexed group column, LATERAL can be faster (see the PostgreSQL docs), but this form works on every major database.
This snippet has been reviewed but was not executed by an automated test. Test it in your own environment before relying on it.
Related snippets
- SQL
Soft delete with a partial unique index
Keep deleted rows but still enforce unique emails among active rows using a partial unique index.
- SQL
Walk a tree with a recursive CTE
Query an employee/manager or category hierarchy to any depth using WITH RECURSIVE.
- SQL
Pivot rows into columns with FILTER
Turn row values into columns (for example monthly totals) using conditional aggregates, without crosstab.
- SQL
Query JSONB and index it with GIN
Filter on JSONB fields with the containment operator and make it fast with a GIN index.

