Window Function Rank Dense Row Number
Compare RANK, DENSE_RANK, and ROW_NUMBER semantics on tied values, picking the right one for leaderboard and quota queries.
Code
-- 三种排序语义在同一数据上的行为差异
WITH scores AS (
SELECT * FROM (VALUES
('ada', 98), ('grace', 98), ('linus', 95),
('margaret', 92), ('katherine', 92), ('alan', 88)
) AS t(player, points)
)
SELECT
player,
points,
ROW_NUMBER() OVER (ORDER BY points DESC) AS row_num,
RANK() OVER (ORDER BY points DESC) AS rank_no,
DENSE_RANK() OVER (ORDER BY points DESC) AS dense_no
FROM scores
ORDER BY points DESC, player;
-- 每组前 N(配额类查询的标准写法)
WITH ranked AS (
SELECT
region,
salesperson,
revenue,
ROW_NUMBER() OVER (
PARTITION BY region ORDER BY revenue DESC
) AS rn
FROM quarterly_revenue
)
SELECT region, salesperson, revenue
FROM ranked
WHERE rn <= 2
ORDER BY region, revenue DESC;What the code does
The script runs more than one SELECT: scores, quarterly_revenue and ranked are the fixtures and results involved.
Mechanically, the statements are built from: a CTE (WITH … AS) that names an intermediate result before the main query; a WHERE clause that scopes which rows one statement can hit; 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.
Statements that matter
WITH ranked AS (
SELECT
region,
salesperson,
revenue,
ROW_NUMBER() OVER (
PARTITION BY region ORDER BY revenue DESC
) AS rn
FROM quarterly_revenue
)
SELECT region, salesperson, revenue
FROM ranked
WHERE rn <= 2
ORDER BY region, revenue DESC;
Interactive Tools for This Topic
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.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.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 tables or CTEs does it reference?
- `scores`, `quarterly_revenue`, `ranked`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.