Leaderboard Rank With Neighbors
Show one player's standing plus adjacent ranks by computing RANK() for the whole board once and filtering a narrow rank window around the target.
Code
CREATE TABLE scores (
player text PRIMARY KEY,
points int NOT NULL
);
INSERT INTO scores VALUES
('ada', 980), ('raj', 980), ('lin', 950),
('kim', 900), ('bob', 870), ('cyd', 860);
-- 先对全榜算一次 RANK,再按目标名次取邻域;标量子查询只跑一次
WITH board AS (
SELECT player, points,
RANK() OVER (ORDER BY points DESC) AS rnk
FROM scores
),
me AS (
SELECT rnk FROM board WHERE player = 'kim'
)
SELECT player, points, rnk
FROM board
WHERE rnk BETWEEN (SELECT rnk FROM me) - 1 AND (SELECT rnk FROM me) + 1
ORDER BY rnk;How the snippet works
SELECT / INSERT / CREATE statements share the script, touching scores, board and me.
Breaking the statements into their working parts: a CTE (WITH … AS) that names an intermediate result before the main query; a WHERE clause narrowing which rows one statement affects; a window function (OVER (…)) computing values across rows without collapsing them; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.
Caveats
- To filter on a window function’s result you need an outer query or CTE; the same-level
WHEREruns too early.
Applying it
The scores table is the working surface here.
Statements that matter
WITH board AS (
SELECT player, points,
RANK() OVER (ORDER BY points DESC) AS rnk
FROM scores
),
me AS (
SELECT rnk FROM board WHERE player = 'kim'
)
SELECT player, points, rnk
FROM board
WHERE rnk BETWEEN (SELECT rnk FROM me) - 1 AND (SELECT rnk FROM me) + 1
ORDER BY rnk;
INSERT INTO scores VALUES
('ada', 980), ('raj', 980), ('lin', 950),
('kim', 900), ('bob', 870), ('cyd', 860);
CREATE TABLE scores (
player text PRIMARY KEY,
points int NOT NULL
);
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.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Name the tables involved in this file.
- The references are `scores`, `board`, `me`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.