Row Number Ties Need Tiebreak

ROW_NUMBER assigns arbitrary order among rows tied on the sort key; add a unique tiebreaker to make numbering, paging, and deduplication reproducible.

SqlData Fetching

Code

snippet
WITH scores(player, points, entered_at) AS (
    VALUES
        ('ada', 900, time '10:00'),
        ('kim', 900, time '10:01'),
        ('raj', 750, time '10:02'),
        ('mei', 750, time '10:03')
),
-- 只按 points 排序:ada/kim 并列 900,两者谁排第一没有保证,
-- 并列行之间的 ROW_NUMBER 分配是未定义的,换计划、换版本就可能换人
-- ROW_NUMBER() OVER (ORDER BY points DESC)          -- 不可复现
numbered AS (
    SELECT
        player,
        points,
        -- 把唯一列接在排序键后面做 tiebreak,编号才可复现
        ROW_NUMBER() OVER (ORDER BY points DESC, entered_at) AS place
    FROM scores
)
SELECT place, player, points, entered_at
FROM numbered
ORDER BY place;
-- 并列分数本该同名次时,用 RANK()/DENSE_RANK(),而不是拿 ROW_NUMBER 硬掰

What the code does

What runs is SELECT, with scores and numbered as the object involved.

What the statements actually assemble: a CTE (WITH … AS) that names an intermediate result before the main query; a window function (OVER (…)) computing values across rows without collapsing them; an ORDER BY that fixes the output order.

What to watch 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 it

Run it in the scores database context.

Interactive Tools for This Topic

FAQ

Which objects does the SQL touch?
`scores`, `numbered`.