← 中文资源

简体中文版本

唯一 tiebreaker 让分页稳定

仅按非唯一列排序翻页时,同值行的归属页不固定,行会重复或丢失:追加唯一键作 tiebreaker 形成全序,复合索引还能顺带免掉排序。

阅读英文原文

实现说明

实际执行的是 SELECT / CREATE——events 是涉及的对象。 语句实际拼装出的结构:ORDER BY 固定了输出顺序;LIMIT 限制返回行数;必填列上的 NOT NULL 限定;强制行身份的 PRIMARY KEY;自动算列值的 GENERATED ALWAYS/GENERATED BY 子句。

常见问题

这段 SQL 涉及哪些对象?

引用的是 events。

核心语句

CREATE TABLE events (
    event_id    bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    happened_at timestamptz NOT NULL
);
SELECT event_id, happened_at
FROM events
ORDER BY happened_at DESC, event_id DESC
LIMIT 50 OFFSET 100;
CREATE INDEX events_recent_idx ON events (happened_at DESC, event_id DESC);

代码示例

-- stable pages need a unique tiebreaker after the sort column
-- sorting only by a non-unique column: rows sharing a key can move between pages, so paging repeats or drops rows
CREATE TABLE events (
    event_id    bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    happened_at timestamptz NOT NULL
);

-- wrong: with several rows sharing happened_at no total order exists
-- SELECT * FROM events ORDER BY happened_at LIMIT 50 OFFSET 100;

-- right: the unique event_id as tiebreaker gives a total order across pages
SELECT event_id, happened_at
FROM events
ORDER BY happened_at DESC, event_id DESC
LIMIT 50 OFFSET 100;

-- the total order matches the composite index exactly, so no extra sort step is needed
CREATE INDEX events_recent_idx ON events (happened_at DESC, event_id DESC);