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.
Code
-- 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
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
- What objects does the SQL involve?
- The references are `events`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.