Before continuing: This entry is part of the window functions guide. If you are new to the topic, start with OVER.
Query
WITH ranked AS (
SELECT
customer_id,
id AS order_id,
date,
total,
ROW_NUMBER() OVER (
PARTITION BY customer_id
ORDER BY date DESC, id DESC
) AS rn
FROM orders
)
SELECT customer_id, order_id, date, total, rn
FROM ranked
WHERE rn <= 2
ORDER BY customer_id, rn;The CTE first calculates a separate position for each customer. The outer query keeps rn <= 2. Customers with a single order appear only once: the pattern does not make up a second row.
How it works
PARTITION BY splits the set into logical groups without collapsing the rows the way GROUP BYwould. Within each partition, ROW_NUMBER() assigns 1, 2, 3… following the ORDER BY clause of the window.
Two different orderings: the ORDER BY within OVER(...) decides who gets rn = 1, rn = 2, etc. The ORDER BY decides how the result is finally presented.
Cases that change the result
Define a deterministic tiebreaker
If two orders share the same date and you only sort by date DESC, its relative order may be left undefined. PostgreSQL documents that ROW_NUMBER() assigns numbers in the window's order and that tied rows may be numbered in an unspecified order. That is why the example adds id DESC as a second criterion.
ROW_NUMBER() OVER (
PARTITION BY customer_id
ORDER BY date DESC, id DESC
)Choose a second criterion that makes sense for your data. Don't add an arbitrary column if it might change the interpretation of “best” or “latest.”
Why the filter goes outside
The position rn is the result of a window function. On the usual engines, you cannot treat that alias as if it already existed in the WHERE at the same query level. The CTE or subquery creates the calculated column first; the outer level can then filter on it.
If this is giving you errors, see the guide window function in WHERE.
ROW_NUMBER, RANK or DENSE_RANK
| Function | Behaviour | When it fits |
|---|---|---|
ROW_NUMBER() | Gives every row a different number. | You want at most N rows per group and you define a tiebreaker. |
RANK() | Tied rows share a position and gaps are left. | You want ties to keep the same competitive position. |
DENSE_RANK() | Tied rows share a position with no gaps. | You want N value levels, even if that produces more than N rows. |
For “exactly the top 2 rows per customer”, ROW_NUMBER() usually expresses the intent best. For “every product tied within the two highest prices”, you may want RANK or DENSE_RANK.
Avoid this confusion
Forgetting PARTITION BY
Without a partition, you number the whole result as a single group and get a global top N, not one per customer, category or entity.
Filtering rn in the same SELECT
Compute the window in a CTE or subquery first, and filter at the outer level.
Not defining a tiebreaker
If the main criterion can repeat and you need reproducible results, add a sensible second criterion.