Order By Tiebreaker Keeps Pages Stable

Append a unique key after the sort column so OFFSET pages follow one total order, and let a matching composite index serve the whole sort.

SqlData Fetching

Code

snippet
-- 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);

How it works

What runs here is SELECT / CREATE — events are the objects involved.

What the statements actually assemble: an ORDER BY that fixes the output order; a row cap (LIMIT) bounding the result size; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.

Applying it

Run the statement against the events table; the LIMIT keeps the probe cheap while you tune the predicates.

Statements that matter

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);

Interactive Tools for This Topic

FAQ

What objects does the SQL involve?
The references are `events`.