Top two order amounts per customer, keeping ties
Question
You have an orders table. For each customer, return every order whose amount is one of that customer's two highest distinct amounts. If two orders share an amount, return both. Sort by customer, then amount descending, then order id.
| order_id | customer_id | amount |
|---|---|---|
| 101 | 1 | 120.00 |
| 102 | 1 | 80.00 |
| 103 | 1 | 120.00 |
| 104 | 1 | 50.00 |
| 201 | 2 | 300.00 |
| 202 | 2 | 90.00 |
| 301 | 3 | 40.00 |
Show hints (2)
- "WHICH FUNCTION"
You need to rank orders inside each customer. Which ranking function gives tied amounts the same rank and leaves no gap after them?
- "WHERE TO FILTER"
Window functions are evaluated after
WHERE, so you can't filter on the rank in the same query level. Wrap it in a CTE or a subquery.
Show checked explanation
Rank each customer's orders with DENSE_RANK(), then keep ranks 1 and 2 in an outer query.
WITH ranked AS ( SELECT order_id, customer_id, amount, DENSE_RANK() OVER ( PARTITION BY customer_id ORDER BY amount DESC ) AS rnk FROM orders ) SELECT order_id, customer_id, amount, rnk FROM ranked WHERE rnk <= 2 ORDER BY customer_id, amount DESC, order_id;
order_id | customer_id | amount | rnk 101 | 1 | 120.00 | 1 103 | 1 | 120.00 | 1 102 | 1 | 80.00 | 2 201 | 2 | 300.00 | 1 202 | 2 | 90.00 | 2 301 | 3 | 40.00 | 1
Query run on PostgreSQL 16 against the data above. Checked by an editor other than the author.
Walkthrough
The three ranking functions only differ on ties. Here is customer 1, ordered by amount descending:
| order | amount | row_number | rank | dense_rank |
|---|---|---|---|---|
| 101 | 120.00 | 1 | 1 | 1 |
| 103 | 120.00 | 2 | 1 | 1 |
| 102 | 80.00 | 3 | 3 | 2 |
| 104 | 50.00 | 4 | 4 | 3 |
ROW_NUMBER() <= 2 returns 101 and 103 and drops the 80.00 order. It counts rows, not amounts, and which of two tied rows gets 1 is arbitrary unless you add a tiebreaker.
RANK() <= 2 also drops 80.00: after a two-way tie the next rank is 3.
DENSE_RANK() <= 2 returns all three rows: two orders at the top amount and one at the second. That is what the task asks for.
Common mistakes
- Writing
WHERE DENSE_RANK() OVER (…) <= 2. PostgreSQL rejects window functions inWHERE; filter one level up. - Using
ORDER BY amount DESC LIMIT 2.LIMITapplies to the whole result, not per customer. - Forgetting
NULL. WithDESC, PostgreSQL sorts nulls first, so a null amount would take rank 1. AddNULLS LASTor exclude nulls if that isn't intended.
Follow-up questions
- "Now return exactly two rows per customer." Use
ROW_NUMBER()with a deterministic tiebreaker:ORDER BY amount DESC, order_id. - "The table has hundreds of millions of rows." An index on
(customer_id, amount DESC)lets aLATERALtop-N per customer read only a few index entries each.
What a strong answer covers
States the tie rule before writing code, names why DENSE_RANK fits, filters in an outer query, and mentions nulls without being asked.
Open in interactive practice deck →