How do you find the top N records in each group?
The top N per group takes two steps: number rows within each group, then keep numbers up to N. A window function with PARTITION BY does the numbering, and it goes into a CTE or subquery because it cannot stand in WHERE. ROW_NUMBER gives at most N rows per group, RANK or DENSE_RANK keep ties, so the requirement is clarified first.
SQL · Window functions
You need the three largest transactions of each account. LIMIT 3 gives three for the whole table. How per group?
A query with ORDER BY amount DESC LIMIT 3 returns the three largest transactions for the whole table, but three per account are needed. LIMIT does not help here: it knows nothing about groups. The classic solution: number the rows inside each group and keep the numbers up to N.
How it works and why. A two-step scheme. First a window function with PARTITION BY numbers the rows in each group in the needed order. Then the outer query keeps rows with a number not above N. Two steps are needed because a window function cannot stand in WHERE: it is computed later.
SELECT dept, name FROM employees
WHERE ROW_NUMBER() OVER (PARTITION BY dept ORDER BY salary DESC) <= 2;
-- ERROR: window functions are not allowed in WHERE
So the first step goes into a CTE (or a subquery) and the filter is applied outside. The sample data: in Dev Anna 9000, Bohdan 8000, Clara 8000, Dmytro 7000, in QA Eva 7000 and Fedir 6000. The two largest salaries of each department:
-- the two largest salaries in each department
WITH ranked AS (
SELECT dept, name, salary,
ROW_NUMBER() OVER (
PARTITION BY dept
ORDER BY salary DESC, name
) AS rn
FROM employees
)
SELECT dept, name, salary
FROM ranked
WHERE rn <= 2
ORDER BY dept, rn;
For Dev these are Anna and Bohdan, for QA Eva and Fedir. Clara, with the same salary as Bohdan, did not get in because ROW_NUMBER gives unique numbers and the second key name settled the tie in favour of Bohdan.
Two functions, two answers
| dept | name | salary |
|---|---|---|
| Dev | Anna | 9000 |
| Dev | Bohdan | 8000 |
| QA | Eva | 7000 |
| QA | Fedir | 6000 |
| dept | name | salary |
|---|---|---|
| Dev | Anna | 9000 |
| Dev | Bohdan | 8000 |
| Dev | Clara | 8000 |
| QA | Eva | 7000 |
| QA | Fedir | 6000 |
If by meaning a tie must be kept ("everyone in the top 2 by salary"), RANK or DENSE_RANK is needed:
-- with RANK the tie stays: Clara is second too
WITH ranked AS (
SELECT dept, name, salary,
RANK() OVER (PARTITION BY dept ORDER BY salary DESC) AS rnk
FROM employees
)
SELECT dept, name, salary FROM ranked WHERE rnk <= 2;
The choice between the functions is a question of requirements, and it is worth clarifying before writing the query: "exactly N" or "everyone in the top".
A QA example. The latest transaction of each account: ROW_NUMBER() OVER (PARTITION BY account_id ORDER BY created_at DESC, id DESC) and the condition rn = 1. The second key id DESC is needed for the case when two transactions share the same time: without it "the latest" may change between runs.
LIMIT against numbering in groups
ORDER BY … LIMIT 2
Two rows for the whole table, not for each department. Groups are not taken into account.
ROW_NUMBER() … rn <= 2
Numbering inside each group, the filter outside. Two rows per department.
Limits and alternatives. PostgreSQL has two other ways. LATERAL applies LIMIT to each group separately and works well when there is an index on the group key and the sort. DISTINCT ON quickly gives the first row of each group, but only one:
-- PostgreSQL: LATERAL applies LIMIT for each department separately
SELECT d.dept, e.name, e.salary
FROM (SELECT DISTINCT dept FROM employees) d
CROSS JOIN LATERAL (
SELECT name, salary
FROM employees x
WHERE x.dept = d.dept
ORDER BY salary DESC, name
LIMIT 2
) e;
-- PostgreSQL: only the largest in a group (Anna, Eva)
SELECT DISTINCT ON (dept) dept, name, salary
FROM employees
ORDER BY dept, salary DESC, name;
Some databases (Snowflake, BigQuery, DuckDB) have QUALIFY, which lets you filter by a window function without a CTE. PostgreSQL and MySQL do not have it. On large tables numbering the whole set costs a sort, so an index on (dept, salary DESC) speeds the query up, and EXPLAIN shows whether it is used.
Typical mistakes.
LIMITwithout grouping: the result is for the whole table, not for a group.- A window function in
WHERE: an error. - Numbering without a unique sort key: on ties the result differs between runs.
RANKinstead ofROW_NUMBERwhere exactly N rows are needed: a tie gives more rows than expected.- Forgetting
ORDER BYin the outer query: the row order after a CTE is not guaranteed.
Check yourself
You are given a query with WHERE rn <= 2 that uses ROW_NUMBER. How does the result in the sample Dev department change if ROW_NUMBER is replaced with RANK?
Answer
With ROW_NUMBER there are two rows, Anna and Bohdan. With RANK the two employees with 8000 both have rank 2, so three rows come back: Anna, Bohdan and Clara.
Why is "top N in each group" not written as one query with LIMIT?
Answer
LIMIT cuts the whole result, not each group. To compute the place inside a group a window function with PARTITION BY is needed, and since it cannot go in WHERE, the filter moves to a CTE or a subquery, or LATERAL is used.