RANK and DENSE_RANK
Overview
RANK gives equal peers the same rank and skips subsequent positions. DENSE_RANK counts distinct ordered peer groups without gaps. ROW_NUMBER instead numbers individual rows. Choose the function according to the reporting meaning, not merely the appearance of the result.
First example
SELECT id, points, RANK() OVER (ORDER BY points DESC) AS r, DENSE_RANK() OVER (ORDER BY points DESC) AS drFROM window_scores WHERE team = 'A' ORDER BY id;Observed SQLite result (rows in JSON):
[ [ 1, 90, 1, 1 ], [ 2, 90, 1, 1 ], [ 3, 70, 3, 2 ], [ 4, 60, 4, 3 ], [ 5, 50, 5, 4 ]]How it works
Team A scores 90, 90, 70, 60, 50 receive ranks 1, 1, 3, 4, 5 and dense ranks 1, 1, 2, 3, 4. Only points belongs in the RANK window ordering if equal scores should share rank. The final output can sort ties by id without changing their ranks. The second example selects the first two competition ranks; team A has no rank 2, while B has two rows tied at rank 2.
Practical example
WITH ranked AS ( SELECT id, team, RANK() OVER (PARTITION BY team ORDER BY points DESC) AS r FROM window_scores)SELECT id, team, r FROM ranked WHERE r <= 2 ORDER BY team, r, id;Observed SQLite result (rows in JSON):
[ [ 1, "A", 1 ], [ 2, "A", 1 ], [ 6, "B", 1 ], [ 7, "B", 2 ], [ 8, "B", 2 ]]Practice and mistakes
Change RANK to DENSE_RANK in the second example: id 3 is now included for A. Compare with ROW_NUMBER <= 2, which returns two rows per team in this fixture. A common error is adding a unique id to RANK and accidentally eliminating score ties. All three forms are supported by the two target engines; only SQLite was run.