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.
Code
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-levelWHEREwill not work — use an outer query or a CTE.
Applying the snippet
Run the statement against the leaderboard table.
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.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- What are the relations in play here?
- `leaderboard`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.