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.

SqlData Fetching

Code

snippet
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 WHERE runs 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

FAQ

Name the tables involved in this file.
The references are `scores`, `board`, `me`.