RANK Skips, DENSE_RANK Does Not

Compare RANK and DENSE_RANK on tied totals: RANK leaves gaps after ties while DENSE_RANK numbers every distinct value consecutively.

SqlData Integrity

Code

snippet
SELECT
    player,
    total_points,
    -- 并列第二之后直接跳到第四:RANK 保留"并列占位"
    RANK() OVER (ORDER BY total_points DESC) AS rank_with_gaps,
    -- 并列第二之后仍是第三:DENSE_RANK 连续编号
    DENSE_RANK() OVER (ORDER BY total_points DESC) AS dense_rank_no_gaps,
    -- ROW_NUMBER 强行编号:并列也要分先后(此处按名字次序)
    ROW_NUMBER() OVER (ORDER BY total_points DESC, player) AS forced_seq,
    -- PERCENT_RANK 把并列转成 0 到 1 的相对位置
    round(PERCENT_RANK() OVER (ORDER BY total_points DESC)::numeric, 2)
        AS relative_standing
FROM leaderboard
ORDER BY total_points DESC, player;

How it works

What runs is SELECT, with leaderboard as the object involved.

Clause by clause, expect: a window function (OVER (…)) computing values across rows without collapsing them; an ORDER BY that fixes the output order.

Watch out for

  • Window functions evaluate after WHERE/GROUP BY, so filtering on their output in the same-level WHERE will not work — use an outer query or a CTE.

Applying the snippet

Run the statement against the leaderboard table.

Interactive Tools for This Topic

FAQ

What are the relations in play here?
`leaderboard`.