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.
Code
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-levelWHEREwill not work — use an outer query or a CTE.
Applying it
Run it in the scores database context.
Interactive Tools for This Topic
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.Number Base ConverterConvert arbitrary-size integers between binary, octal, decimal, hexadecimal, and base 36 with digit validation and signed input support.
FAQ
- Which objects does the SQL touch?
- `scores`, `numbered`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.