Sub topic 5
Sort Order and `ORDER BY` with a Multicolumn Index
This chapter assumes you know basic SELECT, WHERE, ORDER BY, and CREATE INDEX. You should also be able to read the main lines of an EXPLAIN plan.
A B-tree index stores rows in sorted order. PostgreSQL can scan that order instead of finding matching rows and sorting them separately. The index must have the right column order and sort direction for this to work.
Equality first, sort column second
Suppose an application often displays the newest orders for one customer. Create an index with the equality column first and the timestamp second:
CREATE INDEX orders_customer_created_idx
ON orders (customer_id, created_at DESC);
EXPLAIN (COSTS OFF)
SELECT *
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 20;The index groups rows by customer_id. Within each customer group, rows appear from newest to oldest because created_at uses DESC.
The planner can seek directly to the group for customer 42, read entries in index order, and stop after 20 rows. It may use an Index Scan or another index-based plan. The important feature is that no separate Sort node is needed.
Why the first column matters
This index is useful for the following query because it fixes the leading column:
EXPLAIN (COSTS OFF)
SELECT *
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC;This query does not constrain customer_id:
EXPLAIN (COSTS OFF)
SELECT *
FROM orders
WHERE created_at > now() - interval '1 day'
ORDER BY created_at DESC;The index is ordered by customer groups first, not by one global created_at sequence. PostgreSQL would have to inspect many customer groups, so it will often choose another plan and sort the results.
This behavior is called the leftmost-prefix rule. A multicolumn B-tree is most effective when a query constrains a prefix of its columns. Equality conditions usually make the best first columns. A range condition, such as created_at > ..., often limits how later columns can help with searching.
Forward and backward scans
PostgreSQL can scan a B-tree in either direction. An index defined as:
CREATE INDEX orders_customer_created_idx
ON orders (customer_id, created_at DESC);can provide these orders when customer_id is fixed:
ORDER BY created_at DESCORDER BY created_at ASC
A backward scan reverses the complete index order. Because customer_id is fixed to one value, reversing that first column does not affect the result.
With multiple unconstrained sort columns, direction matters more. An index on (x ASC, y DESC) supports (x ASC, y DESC) and its complete reverse, (x DESC, y ASC). It does not directly provide (x ASC, y ASC).
You can specify null placement too:
CREATE INDEX orders_customer_created_nulls_idx
ON orders (customer_id, created_at DESC NULLS LAST);The requested ORDER BY must agree with the index's null ordering if PostgreSQL is to use the index for ordering.
Choosing the index order
Start with the query, not with the table definition.
- Put columns tested by equality in the leading positions.
- Put the main range or sort column after those equality columns.
- Choose
ASCorDESCto match the common ordering. - Check the actual plan with
EXPLAIN. - Keep the index only if it improves an important workload.
Exercise
Why can an index on (customerid, createdat DESC) support ORDER BY createdat DESC for one customer, but not usually support a global ORDER BY createdat DESC query?
Show answer
The index is grouped by customer_id first. Fixing one customer selects one ordered group, but without that filter the timestamp values are interleaved across many customer groups.