8/34
Part 2 of 6 · RankingLearn and do

RANK and DENSE_RANK keep ties at the cutoff, so pick the function your question means

Rank the amounts with RANK instead of ROW_NUMBER, and a top 2 comes back as three rows, because both 45s rank 2:

WITH ranked AS (
    SELECT order_id, amount,
           RANK() OVER (ORDER BY amount DESC) AS rnk
    FROM orders
)
SELECT order_id, amount, rnk
FROM ranked
WHERE rnk <= 2
ORDER BY rnk, order_id;
order_idamountrnk
7501
3452
6452

Here is the same cutoff, <= 2, under each of the three:

OrderAmountROW_NUMBER, tie-break by idRANKDENSE_RANK
#7501, kept1, kept1, kept
#3452, kept2, kept2, kept
#6453, cut2, kept2, kept
#5354, cut4, cut3, cut
Rows kept233

Neither function is wrong. They answer different questions:

  • The two largest, ties to the lower id: ROW_NUMBER with the id in the ORDER BY.
  • Every order tied for a top-2 spot: RANK.
  • Every order at one of the two highest amounts: DENSE_RANK.

RANK and DENSE_RANK split when the tie is at the top:

A and B tie for first, and C has the next amount. Keep <= 2:

RANKDENSE_RANK
A1, kept1, kept
B1, kept1, kept
C3, cut2, kept

Both tied orders get RANK 1, and the next one gets 3, so rank <= 2 stops at the pair. DENSE_RANK gives the next amount a 2 and keeps it.

In the editor, write TOP_TWO_AMOUNTS: every order at one of the two highest amounts, the third question in the list.