Sub topic 5
Sort order and ORDER BY with a multicolumn index
This chapter assumes you can read basic EXPLAIN output and that you know how a multicolumn B-tree index is built and why its column order matters. It uses the orders and users tables from the running schema.
Why an index can replace a sort
A B-tree keeps its entries in sorted order. If the rows a query needs are already stored in the order the query asks for, PostgreSQL can read them straight from the index and skip the sort step. With a LIMIT, it can also stop reading after the first few rows instead of finding and sorting every match.
In a multicolumn index, entries are sorted by the first column. Entries with equal first-column values are sorted by the second column, and so on. This gives one rule that explains most cases:
- If the leading columns are pinned to a single value by equality conditions, the entries that remain are sorted by the next column. The index can supply an
ORDER BYon that next column.
To follow the examples with realistic plans, load some data first. On a tiny table the planner prefers a sequential scan whatever indexes exist.
INSERT INTO orders (customer_id, status, total_cents, created_at)
SELECT (random() * 1000)::int + 1,
'paid',
(random() * 10000)::int,
now() - random() * interval '365 days'
FROM generate_series(1, 200000);
ANALYZE orders;Equality column first, sort column second
Here is the index and query from earlier in the tutorial:
CREATE INDEX orders_customer_created_idx
ON orders (customer_id, created_at DESC);
EXPLAIN
SELECT *
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 20;The plan should look like this (costs omitted):
Limit
-> Index Scan using orders_customer_created_idx on orders
Index Cond: (customer_id = 42)There is no Sort node. The index finds the first entry for customer 42 and walks forward. Those entries are already newest first, so the scan stops after 20 rows.
Indexes can be read in both directions
A B-tree scan can run forward or backward, so one index serves an order and its exact reverse. With the index above, this query also avoids a sort:
EXPLAIN
SELECT *
FROM orders
WHERE customer_id = 42
ORDER BY created_at ASC
LIMIT 20;The plan shows Index Scan Backward using orders_customer_created_idx. For this query the DESC in the index definition is optional. (customer_id, created_at) would serve both ORDER BY created_at ASC and ORDER BY created_at DESC when customer_id is fixed by equality.
When the declared direction matters
The declared direction matters when a query sorts by two or more index columns in different directions. A backward scan reverses every column at once, so an index can only serve two combinations:
| Index definition | Serves `ORDER BY` | Does not serve |
|---|---|---|
| `(a, b)` | `a, b` and `a DESC, b DESC` | `a, b DESC` and `a DESC, b` |
| `(a, b DESC)` | `a, b DESC` and `a DESC, b` | `a, b` and `a DESC, b DESC` |
Suppose you want all orders listed by customer, with each customer's newest order first:
EXPLAIN
SELECT customer_id, created_at, total_cents
FROM orders
ORDER BY customer_id ASC, created_at DESC
LIMIT 50;orders_customer_created_idx matches this exactly, because it was declared as (customer_id, created_at DESC). An index declared as (customer_id, created_at) would not match. The planner would read all the rows and sort them, or it might use an incremental sort, described below.
NULL placement is part of the order
ASC defaults to NULLS LAST. DESC defaults to NULLS FIRST. If your query asks for the other placement, the index must say so too. The users.deleted_at column is nullable, so it shows the effect:
CREATE INDEX users_deleted_at_idx ON users (deleted_at DESC NULLS LAST);
-- Matches the index order, so no Sort is needed:
EXPLAIN
SELECT id FROM users ORDER BY deleted_at DESC NULLS LAST LIMIT 10;
-- Asks for the default DESC placement (NULLS FIRST). A forward scan of this
-- index gives NULLS LAST, and a backward scan gives ASC NULLS FIRST,
-- so neither matches:
EXPLAIN
SELECT id FROM users ORDER BY deleted_at DESC LIMIT 10;Columns declared NOT NULL, such as orders.created_at, never hit this problem. Where NULLs are possible, write the NULLS clause in the index and the query so the two stay in agreement.
Cases where the index cannot supply the order
The rule at the top of the chapter fails in a few common situations.
- The leading column has a range condition.
WHERE customer_id > 40 ORDER BY created_atreads entries for many customers. Each customer's entries are sorted bycreated_at, but the combined stream is not, so PostgreSQL must sort. - The leading column matches several values.
WHERE customer_id IN (1, 2) ORDER BY created_athas the same problem. Two sorted runs are not one sorted run. - The leading column is skipped.
ORDER BY created_atwith no condition oncustomer_idcannot use this index for ordering. The index is sorted by customer first. - The sort uses a different expression.
ORDER BY lower(email)needs an expression index onlower(email). An index onemaildoes not help.
PostgreSQL 13 and later has a partial rescue, the incremental sort. If the index supplies the leading part of the sort key, PostgreSQL sorts only within each group of equal prefix values. For example, an index on (customer_id) alone with ORDER BY customer_id, created_at can show an Incremental Sort node over an index scan. It is cheaper than a full sort. It is still slower than an index that supplies the whole order, because it must read each group completely before emitting rows.
Add a tiebreaker for stable pagination
Sorting by created_at alone gives an undefined order among rows with the same timestamp. Paging through such results can skip or repeat rows. Add a unique column to the sort and to the index:
CREATE INDEX orders_customer_created_id_idx
ON orders (customer_id, created_at DESC, id DESC);
EXPLAIN
SELECT id, created_at, total_cents
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC, id DESC
LIMIT 20;This query is still served in index order. It also supports keyset pagination, where the next page asks for rows strictly before the last row seen:
SELECT id, created_at, total_cents
FROM orders
WHERE customer_id = 42
AND (created_at, id) < (TIMESTAMPTZ '2026-06-01 12:00:00+00', 123456)
ORDER BY created_at DESC, id DESC
LIMIT 20;The row comparison (created_at, id) < (...) matches the index's column order, so PostgreSQL can use it as an index condition. The cost of each page stays the same however deep you page. OFFSET paging gets slower with every page because it must step over all the skipped rows.
Checking your work
- Run
EXPLAINand look for aSortnode. If one sits above the scan, the index did not supply the order. - Check that the scan is an
Index Scan(orIndex Scan Backward), not aBitmap Heap Scan. Bitmap scans return rows in table order, so they cannot supply any ordering. - Without
LIMIT, the planner may still choose a sequential scan plus sort, because reading a large share of the table through an index is slower. The ordering benefit is largest when aLIMITlets the scan stop early.
Exercise
A table has the index CREATE INDEX t_idx ON t (a, b DESC). For each query, say whether the index can supply the order without a Sort node, assuming the planner chooses to use it: (1) WHERE a = 5 ORDER BY b, (2) ORDER BY a DESC, b, (3) ORDER BY a, b, (4) WHERE a > 5 ORDER BY b DESC.
Show answer
(1) Yes. With a fixed, entries are sorted by b DESC, and a backward scan returns b ASC. (2) Yes. A backward scan of the index gives a DESC, b ASC. (3) No. The index gives a, b DESC or a DESC, b, not a, b, so PostgreSQL needs a Sort, or an incremental sort on a in PostgreSQL 13 and later. (4) No. The range on a means entries from many a values are read, so b is not globally sorted.