Row Number Renumbers Sequence Gaps

After deletions leave playlist positions with gaps, ROW_NUMBER over the remaining order feeds an UPDATE through a CTE to restore 1..N.

SqlData Integrity

Code

snippet
-- 曲目删除后 position 留下 gaps(2 之后直接是 5、9)
-- ROW_NUMBER 沿原 sequence 生成 1..N 的新编号,经 CTE 中转回写 UPDATE
CREATE TEMP TABLE playlist_tracks (
    playlist_id int NOT NULL,
    track_id    int NOT NULL,
    position    int NOT NULL,
    PRIMARY KEY (playlist_id, track_id)
);
INSERT INTO playlist_tracks VALUES
    (1, 101, 1),
    (1, 102, 2),
    (1, 103, 5),
    (1, 104, 9);

WITH renumbered AS (
    SELECT
        playlist_id,
        track_id,
        ROW_NUMBER() OVER (PARTITION BY playlist_id ORDER BY position) AS next_position
    FROM playlist_tracks
)
UPDATE playlist_tracks pt
SET position = r.next_position
FROM renumbered r
WHERE pt.playlist_id = r.playlist_id
  AND pt.track_id = r.track_id;

SELECT position, track_id
FROM playlist_tracks
WHERE playlist_id = 1
ORDER BY position;

Row Number Renumbers Sequence Gaps: what runs and why

SELECT / INSERT / UPDATE / CREATE statements share the script, touching playlist_tracks and renumbered.

playlist_tracks materializes as a session-local temp table the moment the file runs — nothing to prepare ahead, nothing survives the session.

Concretely, the SQL combines: a CTE (WITH … AS) that names an intermediate result before the main query; a WHERE clause bounding the rows one statement applies to; a window function (OVER (…)) evaluating per-row over a window while keeping every row in the output; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.

What to watch for

  • Window functions evaluate after WHERE/GROUP BY, so filtering on their output in the same-level WHERE will not work — use an outer query or a CTE.

Putting it to use

No pre-made schema needed: the file defines playlist_tracks itself — run it wholesale on a scratch database.

Core lines

SELECT position, track_id
FROM playlist_tracks
WHERE playlist_id = 1
ORDER BY position;
CREATE TEMP TABLE playlist_tracks (
    playlist_id int NOT NULL,
    track_id    int NOT NULL,
    position    int NOT NULL,
    PRIMARY KEY (playlist_id, track_id)
);
INSERT INTO playlist_tracks VALUES
    (1, 101, 1),
    (1, 102, 2),
    (1, 103, 5),
    (1, 104, 9);

Interactive Tools for This Topic

FAQ

Which tables or CTEs does it reference?
The references are `playlist_tracks`, `renumbered`.