man postgres/sorting-and-paging
lesson 7 of 34 · Querying
Sorting and paging
The three best-rated orders:
SELECT id, rating
FROM orders
ORDER BY rating DESC, id
LIMIT 3;id | rating -----+-------- 102 | 103 | 105 | (3 rows)
Three orders with no rating at all. In PostgreSQL a NULL sorts as if it were larger than every value, so an ascending sort puts the NULLs last and a descending sort puts them first, at the top of a “best” list. Saying where they go fixes it:
SELECT id, rating
FROM orders
ORDER BY rating DESC NULLS LAST, id
LIMIT 3;id | rating -----+-------- 101 | 5 111 | 5 104 | 4 (3 rows)
ORDER BY looks like the simplest clause in a query, but it decides more than it seems: where the NULLs go, how text compares, which of two equal rows comes first, and, through LIMIT and OFFSET, which rows a page shows. This lesson takes those in turn and ends with paging through a large result, where the obvious way, OFFSET, gets slower the further the reader goes and can show a row twice.
The data
The customers and orders of the lesson on NULL, unchanged. A product list whose names and lot codes show how text sorts, and an archive of 100,000 older orders, generated, to measure paging on more than twelve rows:
CREATE TABLE products (
id integer PRIMARY KEY,
name text NOT NULL,
origin text NOT NULL,
price numeric(6,2) NOT NULL,
lot text NOT NULL
);
CREATE TABLE orders_archive (
id integer PRIMARY KEY,
ordered_on date NOT NULL,
total numeric(8,2) NOT NULL
);
CREATE INDEX archive_by_date ON orders_archive (ordered_on, id);
SELECT * FROM products ORDER BY id;id | name | origin | price | lot ----+-------------+----------+-------+--------- 1 | Yirgacheffe | Ethiopia | 14.50 | lot 12 2 | Huila | Colombia | 12.00 | lot 7 3 | Santos | Brazil | 9.75 | lot 103 4 | Kiambu | Kenya | 16.25 | lot 9 5 | decaf Huila | Colombia | 13.00 | lot 21 6 | Évora blend | Brazil | 11.50 | lot 110 (6 rows)
SELECT count(*), min(ordered_on), max(ordered_on)
FROM orders_archive;count | min | max --------+------------+------------ 100000 | 2019-01-01 | 2025-11-05 (1 row)
The setup script has the details. Every box on this page gives the same output live as recorded, except one, which says so next to it.
Directions and NULLs
Each sort key has a direction, ASC (the default) or DESC, and a place for
NULLs, NULLS FIRST or NULLS LAST. If the place is not given, it follows the
direction: NULLS LAST for ASC and NULLS FIRST for DESC, as if NULL were the
largest value. The six shipped orders have four ratings and two NULLs,
written here as -:
SELECT string_agg(coalesce(rating::text, '-'), ' ' ORDER BY rating) AS "ASC",
string_agg(coalesce(rating::text, '-'), ' ' ORDER BY rating DESC) AS "DESC",
string_agg(coalesce(rating::text, '-'), ' ' ORDER BY rating DESC NULLS LAST) AS "DESC NULLS LAST",
string_agg(coalesce(rating::text, '-'), ' ' ORDER BY rating NULLS FIRST) AS "ASC NULLS FIRST"
FROM orders
WHERE status = 'shipped';ASC | DESC | DESC NULLS LAST | ASC NULLS FIRST -------------+-------------+-----------------+----------------- 2 4 5 5 - - | - - 5 5 4 2 | 5 5 4 2 - - | - - 2 4 5 5 (1 row)
(The ORDER BY inside string_agg, from the lesson on aggregates, accepts
the same options as the query’s own.) Writing NULLS FIRST or NULLS LAST
whenever a sort key can be NULL saves the next reader from remembering the
default, and tells them that you thought about it.
The direction belongs to one key, not to the whole ORDER BY. This sorts by status ascending and, within each status, by total descending:
SELECT id, status, total
FROM orders
ORDER BY status, total DESC, id;id | status | total -----+-----------+------- 103 | cancelled | 60.00 112 | cancelled | 15.00 106 | cancelled | 12.00 110 | paid | 64.00 105 | paid | 31.00 107 | paid | 27.50 108 | shipped | 99.90 104 | shipped | 75.25 101 | shipped | 42.00 111 | shipped | 42.00 109 | shipped | 23.75 102 | shipped | 18.50 (12 rows)
A sort key can be any expression, including one that is not in the select list. A CASE gives an order that is neither alphabetical nor numeric, such as the order an order moves through:
SELECT id, status, total
FROM orders
ORDER BY CASE status WHEN 'paid' THEN 1 WHEN 'shipped' THEN 2 ELSE 3 END,
id;id | status | total -----+-----------+------- 105 | paid | 31.00 107 | paid | 27.50 110 | paid | 64.00 101 | shipped | 42.00 102 | shipped | 18.50 104 | shipped | 75.25 108 | shipped | 99.90 109 | shipped | 23.75 111 | shipped | 42.00 103 | cancelled | 60.00 106 | cancelled | 12.00 112 | cancelled | 15.00 (12 rows)
Collations: how text compares
Sorting the product names gives this:
SELECT name FROM products ORDER BY name;name ------------- Huila Kiambu Santos Yirgacheffe decaf Huila Évora blend (6 rows)
decaf Huila after Yirgacheffe, and Évora blend last. Text is compared
by a collation, a set of rules for ordering strings, and every database
has a default one, chosen when the database is created. The databases of
this course use C, both the server that recorded the outputs and the one
in this page:
SELECT datcollate FROM pg_database WHERE datname = current_database();datcollate ------------ C (1 row)
C compares the bytes of the strings. That is fast and the same on every
platform, but it is not how people alphabetise: every uppercase ASCII
letter comes before every lowercase one, and a letter with an accent, whose
UTF-8 bytes are larger than any ASCII letter’s, comes after both. Many
servers are created with a language’s locale as the default instead, and
then sort these names more like the next box does; the details depend on
the locale, and on the library that provides it.
A COLLATE clause picks a collation for one expression. "unicode" is one
of the collations every PostgreSQL built with ICU (the International
Components for Unicode library) provides: the Unicode root order, which
ignores case and accents at first, and uses them only to break ties. Its
exact rules come from the ICU version PostgreSQL was built with; the server
and PGlite use different versions, and they agree on these names:
SELECT name FROM products ORDER BY name COLLATE "unicode";name ------------- decaf Huila Évora blend Huila Kiambu Santos Yirgacheffe (6 rows)
The collation decides comparisons too, not only sorts: <, min, max,
and range conditions on text all follow it.
SELECT 'decaf' < 'Huila' AS c,
'decaf' < 'Huila' COLLATE "unicode" AS unicode;c | unicode ---+--------- f | t (1 row)
Neither collation sorts numbers inside text as numbers. The lot codes come
out with lot 103 before lot 7, because the character 1 comes before
7:
SELECT name, lot FROM products ORDER BY lot;name | lot -------------+--------- Santos | lot 103 Évora blend | lot 110 Yirgacheffe | lot 12 decaf Huila | lot 21 Huila | lot 7 Kiambu | lot 9 (6 rows)
ICU can: its locale names take options, and und-u-kn means the root
locale (und) with numeric ordering (kn) switched on. The setup script
creates a collation from it:
CREATE COLLATION numeric_order (provider = icu, locale = 'und-u-kn');
SELECT name, lot FROM products ORDER BY lot COLLATE numeric_order;name | lot -------------+--------- Huila | lot 7 Kiambu | lot 9 Yirgacheffe | lot 12 decaf Huila | lot 21 Santos | lot 103 Évora blend | lot 110 (6 rows)
This box differs in the page. PGlite, the PostgreSQL 19.0 build that
runs the boxes here, accepts the collation but ignores the option (and
other locale-specific rules, as far as we tested), and sorts by the root
order: lot 103, lot 110, lot 12, lot 21, lot 7, lot 9. The
recording above is the native server’s.
Two practical points. An index on a text column is built in one collation, and it can only serve an ORDER BY or a range condition in that same collation. And when the order must be the same in every database, sort by something that does not depend on a collation, such as a number, or give the collation explicitly.
Ties
When two rows have equal sort keys, ORDER BY says nothing about which comes
first, and the answer can change from one run to the next, or with the
plan. The first lesson showed what that does to a LIMIT that cuts through a
tie. A unique last key, usually the primary key, makes the order total, and
every query whose result is cut into pieces needs one. The boxes in this
lesson that list rows end with id for that reason, apart from those whose
keys are already unique and the WITH TIES box below.
Sometimes the tie is the point: “the best-rated order” when two orders
share the best rating. FETCH FIRST n ROWS WITH TIES returns the first n
rows plus every row that ties with the last of them:
SELECT id, rating
FROM orders
ORDER BY rating DESC NULLS LAST
FETCH FIRST 1 ROW WITH TIES;id | rating -----+-------- 111 | 5 101 | 5 (2 rows)
Both 5s. Their order among themselves is still not defined; this run listed 111 first. Ties are decided by the ORDER BY, so WITH TIES without one is an error:
SELECT id, rating
FROM orders
FETCH FIRST 1 ROW WITH TIES;ERROR: WITH TIES cannot be specified without ORDER BY clause
LINE 3: FETCH FIRST 1 ROW WITH TIES;
^FETCH FIRST n ROWS ONLY and OFFSET n ROWS are the SQL standard’s
spelling of LIMIT and OFFSET, which PostgreSQL also accepts; WITH TIES
exists only in the standard form.
Paging with OFFSET
An application that shows orders newest first, four to a page, usually asks
for page n with LIMIT 4 OFFSET 4 * (n - 1). Page 2:
SELECT id, ordered_on, total
FROM orders
ORDER BY ordered_on DESC, id DESC
LIMIT 4 OFFSET 4;id | ordered_on | total -----+------------+------- 108 | 2026-03-13 | 99.90 107 | 2026-03-12 | 27.50 106 | 2026-03-10 | 12.00 105 | 2026-03-09 | 31.00 (4 rows)
OFFSET has two problems. The first is cost. OFFSET does not jump to a row: the server has to produce the skipped rows, in order, and throw them away. On the archive, page 5,001 of ten rows each, with EXPLAIN ANALYZE showing how many rows each step of the plan returned (timings and costs off):
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT id, ordered_on, total
FROM orders_archive
ORDER BY ordered_on, id
LIMIT 10 OFFSET 50000; QUERY PLAN
-----------------------------------------------------------------------------------------
Limit (actual rows=10.00 loops=1)
-> Index Scan using archive_by_date on orders_archive (actual rows=50010.00 loops=1)
Index Searches: 1
(3 rows)The index scan returned 50,010 rows so that the Limit could pass on ten. The deeper the reader goes, the more rows each page reads and throws away.
The second problem is that the pages move. Each page is a separate query, and if rows are added or removed between two requests, every row after the change shifts by that many places. A row can then show up on two pages, or on none. The figure below shows both methods of this lesson paging through the orders while a new order arrives.
Keyset pagination
The other way to ask for the next page is to say where the last one ended.
The last row of page 1 was order 109, from 2026-03-15. Page 2 is the rows
that sort after it, which in a descending order means the rows whose
(ordered_on, id) is smaller:
SELECT id, ordered_on, total
FROM orders
WHERE (ordered_on, id) < ('2026-03-15', 109)
ORDER BY ordered_on DESC, id DESC
LIMIT 4;id | ordered_on | total -----+------------+------- 108 | 2026-03-13 | 99.90 107 | 2026-03-12 | 27.50 106 | 2026-03-10 | 12.00 105 | 2026-03-09 | 31.00 (4 rows)
(a, b) < (x, y) is a row comparison. It compares the first fields, and
only if they are equal goes on to the second, like sorting words letter by
letter; it means a < x OR (a = x AND b < y). That is exactly “comes before
in an ORDER BY a, b”, which is why the tiebreaker must be part of the key:
with ordered_on alone, the next page would skip the rest of a day whose
first orders ended the previous page.
The 12 orders sorted newest first, in pages of 4. Page 1 is orders 112, 111, 110 and 109 either way. Then order 113 arrives and sorts first. Page 2 with OFFSET 4 skips 113, 112, 111 and 110 and returns 109 again, then 108, 107 and 106. Page 2 with the keyset returns 108, 107, 106 and 105. Page 3 with OFFSET 8 returns 105 to 102; with the keyset, 104 to 101. OFFSET shows order 109 twice; the keyset pages show each order once. (This figure steps through a recorded run; it needs JavaScript.)
Every list and page comes from a query run against PostgreSQL 19.0 by the
lesson’s trace.py, with the new order inserted in the same transaction
before the page 2 queries. Struck-through rows are the ones OFFSET skips:
produced and thrown away.
The keyset query also fixes the cost, if an index matches the ORDER BY. The condition becomes the start of an index scan, and the scan reads only the rows it returns. To ask for page 5,001 of the archive that way, the application needs the key of the last row of page 5,000, which it showed the reader before. Here it is, looked up with OFFSET for once:
SELECT id, ordered_on, total
FROM orders_archive
ORDER BY ordered_on, id
LIMIT 1 OFFSET 49999;id | ordered_on | total -------+------------+------- 50000 | 2022-06-04 | 60.00 (1 row)
Page 5,001 is then “the ten rows after ('2022-06-04', 50000)”:
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT id, ordered_on, total
FROM orders_archive
WHERE (ordered_on, id) > ('2022-06-04', 50000)
ORDER BY ordered_on, id
LIMIT 10; QUERY PLAN
--------------------------------------------------------------------------------------
Limit (actual rows=10.00 loops=1)
-> Index Scan using archive_by_date on orders_archive (actual rows=10.00 loops=1)
Index Cond: (ROW(ordered_on, id) > ROW('2022-06-04'::date, 50000))
Index Searches: 1
(4 rows)Ten rows read, where OFFSET read 50,010 for the same page. The row comparison appears in the
plan as the Index Cond, the place where the scan starts. The same
condition written out with OR means the same, but in this plan it is only a
Filter: the scan starts at the beginning of the index and throws away
every row before the key.
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT id, ordered_on, total
FROM orders_archive
WHERE ordered_on > '2022-06-04' OR (ordered_on = '2022-06-04' AND id > 50000)
ORDER BY ordered_on, id
LIMIT 10; QUERY PLAN
-------------------------------------------------------------------------------------------------------------
Limit (actual rows=10.00 loops=1)
-> Index Scan using archive_by_date on orders_archive (actual rows=10.00 loops=1)
Filter: ((ordered_on > '2022-06-04'::date) OR ((ordered_on = '2022-06-04'::date) AND (id > 50000)))
Rows Removed by Filter: 50000
Index Searches: 1
(5 rows)Keyset pagination has conditions of its own:
- The key must be unique and never NULL. A row comparison that reaches a NULL field is NULL, not true or false, so a row with a NULL key can be missing from every page. Use NOT NULL columns, ending with the primary key.
- All keys in one direction. A row comparison works for
ORDER BY a, band forORDER BY a DESC, b DESC. For mixed directions such asORDER BY a, b DESC, the condition has to be written out,a > x OR (a = x AND b < y), and as the last box showed, the plan may then read more than it returns. Check it with EXPLAIN. - No jumping. There is “next page” and, with the comparison and the sort reversed, “previous page”, but no “page 37”. For an infinite scroll or a feed that is all you need; for numbered pages over a big result it is not, and some applications keep OFFSET for the first few pages only.
- The same collation as the index, when a key is text.
Try it yourself
Use any box above: press “edit”, replace the query, press “run”. The queries in the answers can be pasted the same way.
- List the shipped orders by how long they took to ship, slowest first,
with the unrated ones last among equally slow orders and
idas the final tiebreaker.
Answer
Three keys, each with its own direction:
SELECT id, shipped_on - ordered_on AS days, rating
FROM orders
WHERE status = 'shipped'
ORDER BY shipped_on - ordered_on DESC, rating DESC NULLS LAST, id;
Order 108 took 3 days; 102 took 2; 101 and 111 one each, both rated 5, so
id decides between them.
- Show the most expensive order of each status, with every order that ties for the top total within that status. One query, no window functions.
Answer
WITH TIES works on the whole result, not per group, so it cannot do this alone. A correlated subquery from the previous lesson can:
SELECT id, status, total
FROM orders AS o
WHERE total = (SELECT max(total) FROM orders AS i WHERE i.status = o.status)
ORDER BY status, id;
One order per status here: 103 (cancelled, 60.00), 110 (paid, 64.00) and 108 (shipped, 99.90).
- Page 2 of the products in the
"unicode"order, two per page, with a keyset afterÉvora blend.
Answer
The comparison must use the same collation as the sort, or the page
boundary and the order disagree. name is not unique by declaration, so a
real application would add id to the key; the names here happen to be
different.
SELECT name
FROM products
WHERE name COLLATE "unicode" > 'Évora blend'
ORDER BY name COLLATE "unicode"
LIMIT 2;
Huila and Kiambu.
- Write the keyset query for the page of the archive that comes before
the row
('2022-06-04', 50000), ten rows, in the usual ascending order.
Answer
Reverse the comparison and the sort to walk backwards from the key, then sort the ten rows forwards again in an outer query:
SELECT *
FROM (SELECT id, ordered_on, total
FROM orders_archive
WHERE (ordered_on, id) < ('2022-06-04', 50000)
ORDER BY ordered_on DESC, id DESC
LIMIT 10) AS page
ORDER BY ordered_on, id;
Orders 49990 to 49999.
- Page 2 of the orders, newest first, ended with order 105 from 2026-03-09. Write the keyset query for page 3, and check it against the OFFSET version.
Answer
Both return orders 104, 103, 102 and 101, as long as nothing changes between the requests:
SELECT id, ordered_on, total
FROM orders
WHERE (ordered_on, id) < ('2026-03-09', 105)
ORDER BY ordered_on DESC, id DESC
LIMIT 4;
SELECT id, ordered_on, total
FROM orders
ORDER BY ordered_on DESC, id DESC
LIMIT 4 OFFSET 8;
Sources
The PostgreSQL 19 documentation:
- Sorting rows: ASC and DESC, NULLS FIRST and LAST and their defaults, sorting by expressions and output columns.
- LIMIT and OFFSET: why a result cut into pieces needs an ORDER BY that fixes the order, and why a large OFFSET is slow.
- SELECT: the ORDER BY, LIMIT and FETCH clauses, including WITH TIES.
- Collation support:
the database default, the COLLATE clause, the predefined
"unicode"collation and ICU locale options such askn. - Row and array comparisons: row constructor comparisons, compared field by field.
- Indexes and ORDER BY and multicolumn indexes.
- Using EXPLAIN.
ls postgres/
Querying
- 01 How a SELECT runs, clause by clause draftThe logical order of FROM, WHERE, GROUP BY, HAVING, SELECT, DISTINCT, ORDER BY and LIMIT, and the everyday errors it explains.
- 02 Tables and the types worth knowing draftinteger and bigint, numeric against double precision, text, boolean, uuid (including uuidv7), identity columns, and casts.
- 03 NULL and three-valued logic draftWhy x = NULL is never true, IS DISTINCT FROM, coalesce, NOT IN with a NULL in the list, and how aggregates skip NULLs.
- 04 Joins draftInner, left, right, full and cross joins; ON against USING; semi- and anti-joins with EXISTS; the rows an outer join adds.
- 05 Aggregates and GROUP BY draftcount(*) against count(x), FILTER, ordered string_agg and array_agg, any_value, and grouping by a primary key.
- 06 Subqueries and set operations draftScalar, IN, EXISTS, ANY and ALL subqueries, correlated subqueries, and UNION, INTERSECT and EXCEPT with and without ALL.
- 07 Sorting and paging draftNULLS FIRST and LAST, collations, ties and FETCH ... WITH TIES, and keyset pagination instead of large OFFSETs.
- 08 Dates, times and time zones plannedtimestamp against timestamptz, the session time zone, intervals, date_trunc, and generate_series for calendars.
- 09 Changing data plannedINSERT, UPDATE and DELETE with RETURNING, including OLD and NEW values in RETURNING, and UPDATE ... FROM.
Analytical queries
- 10 Window functions plannedPARTITION BY, ORDER BY and frames; ranking, running totals and moving averages; lag, lead and first_value with IGNORE NULLS.
- 11 WITH queries plannedCommon table expressions for readability, MATERIALIZED and NOT MATERIALIZED, and data-modifying statements in WITH.
- 12 Recursive queries plannedWITH RECURSIVE over trees and graphs, the SEARCH and CYCLE clauses, and how to stop a recursion that never ends.
- 13 LATERAL plannedSubqueries and functions that see the row beside them: top N per group, and set-returning functions per row.
- 14 GROUPING SETS, ROLLUP and CUBE plannedSeveral groupings in one query, subtotals and grand totals, and telling them apart with GROUPING().
Richer data
- 15 JSONB plannedOperators, containment, jsonpath, updating documents, and the GIN indexes that make the queries fast.
- 16 SQL/JSON and JSON_TABLE plannedThe standard JSON functions: JSON_VALUE, JSON_QUERY, JSON_EXISTS, IS JSON, and JSON_TABLE to turn documents into rows.
- 17 Arrays plannedBuilding and slicing arrays, unnest WITH ORDINALITY, = ANY, array_agg, array_sort, and when a table is better.
- 18 Ranges and temporal keys plannedRange and multirange types, overlap and containment, exclusion constraints, and primary keys WITHOUT OVERLAPS.
- 19 Full-text search plannedtsvector and tsquery, configurations and dictionaries, ranking, highlighting, and indexing a search column.
Keeping data correct
- 20 Constraints plannedCHECK, NOT NULL, UNIQUE with NULLS NOT DISTINCT, foreign keys and their actions, deferrable constraints, NOT VALID.
- 21 Generated columns plannedColumns computed from others, virtual (the default) or stored, and what each costs on reads and writes.
- 22 Transactions and isolation levels plannedWhat READ COMMITTED, REPEATABLE READ and SERIALIZABLE let two sessions see, the anomalies each allows, and retrying serialization failures.
- 23 Row locks and queues plannedSELECT ... FOR UPDATE and its weaker forms, NOWAIT, SKIP LOCKED for job queues, and advisory locks.
- 24 Upsert and MERGE plannedINSERT ... ON CONFLICT DO NOTHING, DO UPDATE and DO SELECT; MERGE with WHEN NOT MATCHED BY SOURCE and RETURNING merge_action().
Performance from the query side
- 25 Indexes plannedWhat a B-tree index can answer: column order in multicolumn indexes, partial, expression and covering (INCLUDE) indexes.
- 26 GIN, GiST, BRIN and hash plannedWhich queries each index type serves, with the operators that use it: containment, overlap, nearest neighbour, ranges of a big table.
- 27 Reading EXPLAIN plannedPlan nodes, estimated against actual rows, buffers, and the questions to ask of a slow plan. How statistics feed the estimates.
- 28 Partitioning plannedRange, list and hash partitions, partition pruning in plans, and attaching and detaching partitions.
Logic and access in the database
- 29 Views and materialized views plannedNaming a query, updatable views, WITH CHECK OPTION, and refreshing a materialized view concurrently.
- 30 SQL and PL/pgSQL functions plannedFunctions and procedures, volatility, set-returning functions, and PL/pgSQL control flow and error handling.
- 31 Triggers plannedRow and statement triggers, BEFORE and AFTER, transition tables, and keeping an audit log.
- 32 LISTEN and NOTIFY plannedMessages between sessions, how they interact with transactions, and a small change feed.
- 33 Row-level security plannedPolicies that filter rows per role, USING against WITH CHECK, and the roles that bypass them.
- 34 Extensions worth knowing plannedpg_trgm, pgcrypto, citext, btree_gist, postgres_fdw and pg_stat_statements: what each adds and when to reach for it.