Sub topic 4
Why column order matters
This chapter assumes you can read basic EXPLAIN output and know that a B-tree index keeps entries in sorted order. It uses the orders table from the running schema. Here you will learn how a multicolumn B-tree index orders its entries, which conditions narrow the part of the index that is read, and how to pick a column order from a query's needs.
The index is one sorted list
A multicolumn B-tree index does not hold one tree per column. It holds a single sorted list of entries. Entries are sorted by the first column. Rows with equal first-column values are sorted by the second column, and so on.
A phone book works the same way. It is sorted by last name, then first name. You can find "Smith, Ada" quickly. You cannot find every "Ada" quickly, because the Adas are scattered across all the last names.
For orders_customer_created_idx ON orders (customer_id, created_at DESC), the entries look like this:
| customer_id | created_at (descending within customer) |
|---|---|
| 41 | 2026-03-02 |
| 41 | 2026-01-10 |
| 42 | 2026-04-19 |
| 42 | 2026-02-27 |
| 42 | 2026-02-01 |
| 43 | 2026-05-05 |
All entries for customer 42 sit next to each other, with the newest first. The search descends the tree to the first entry for customer 42 and reads forward. That adjacency is what makes this index fast.
What the planner can use to narrow the scan
The PostgreSQL documentation states the rule this way: equality constraints on leading columns, plus an inequality constraint on the first column that has no equality constraint, limit the portion of the index that is scanned. Constraints on columns to the right of those are still checked inside the index. That saves visits to the table, but it does not shrink the scanned range.
Take an index on (a, b, c) and these conditions:
| Query conditions | Bounds the scan | Checked inside the index only |
|---|---|---|
| `a = 1 AND b = 2 AND c > 5` | `a`, `b`, and `c` | none |
| `a = 1 AND b > 2 AND c = 5` | `a` and `b` | `c` |
| `a > 1 AND b = 2` | `a` | `b` |
| `b = 2` | nothing (older releases) | `b` |
In the third row, a > 1 is a range. The matching entries are spread across many values of a, and within each of them the entries with b = 2 are a separate slice. The scan must pass through everything between the lowest and highest a.
A worked comparison
This script builds a test table you can run as written. It fills orders with 200,000 rows spread over 1,000 customers and one year.
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id bigint NOT NULL,
status text NOT NULL,
total_cents integer NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO orders (customer_id, status, total_cents, created_at)
SELECT (random() * 999)::bigint + 1,
(ARRAY['pending', 'paid', 'shipped'])[1 + floor(random() * 3)::int],
(random() * 50000)::int,
now() - random() * interval '365 days'
FROM generate_series(1, 200000);
ANALYZE orders;Now create two indexes with the same columns in opposite order, and test one query against each.
CREATE INDEX orders_cust_created_idx ON orders (customer_id, created_at);
CREATE INDEX orders_created_cust_idx ON orders (created_at, customer_id);
EXPLAIN (ANALYZE, BUFFERS)
SELECT id
FROM orders
WHERE customer_id = 42
AND created_at > now() - interval '30 days';The planner will probably choose orders_cust_created_idx. It descends to customer 42, then to the first entry within the last 30 days, and reads only the matching entries. To see the other index's cost, drop the first one inside a transaction and roll back. DROP INDEX takes a strong lock on the table, so do this only on a test database.
BEGIN;
DROP INDEX orders_cust_created_idx;
EXPLAIN (ANALYZE, BUFFERS)
SELECT id
FROM orders
WHERE customer_id = 42
AND created_at > now() - interval '30 days';
ROLLBACK;With (created_at, customer_id), only the range on created_at bounds the scan. The scan covers every order from the last 30 days, which is about 16,000 rows here, and tests customer_id = 42 on each entry. Compare the Buffers: shared hit counts and the execution times in the two plans. The first plan touches a few pages. The second reads far more of the index to return the same dozen rows or so.
Rules for choosing the order
- Put equality columns first. Columns compared with
=(orINwith a short list) go to the left. They narrow the scan to one contiguous block. - Put the range or sort column next. A range condition (
>,<,BETWEEN) or anORDER BYcolumn goes after the equality columns. The entries in the block are then already ordered by it. - Stop at the first range column. Columns after a range column help only as in-index filters. Adding them is sometimes worthwhile, because it avoids table visits, but they will not narrow the scan.
- Order the equality columns by reuse. Among equality columns, put first the one that more queries filter on by itself. That lets one index serve several queries.
Rule 1 contradicts a common claim that the most selective column should come first. Selectivity matters mainly among columns that are all compared with equality. A highly selective column used only as a range condition still belongs after the equality columns, because a range on a leading column breaks the contiguous block.
Example: a status filter
Suppose a dashboard runs WHERE status = 'pending' ORDER BY created_at LIMIT 50. The right index is (status, created_at). The planner descends to the first pending entry and reads 50 entries in order, with no sort step. The reverse order, (created_at, status), can also return rows in order, but it must walk the whole time range and skip entries that do not match. If pending is rare, the walk goes through many entries before it finds 50.
Queries that skip the leading column
The second query in the chapter's earlier examples filters only on created_at:
EXPLAIN
SELECT *
FROM orders
WHERE created_at > now() - interval '1 day';With orders_customer_created_idx (customer_id, created_at DESC), the leading column is not constrained. In releases before PostgreSQL 18, the planner has two choices. It can scan the whole index and test created_at on each entry. More often it prefers a sequential scan of the table, or an index on created_at if one exists. Both of these read far more than the 1-day slice you want.
PostgreSQL 18 added skip scan. It can use a multicolumn index when the leading column has no condition, by jumping from one distinct leading value to the next. It pays off only when the leading column has few distinct values, such as a status with three values. With 1,000 customers, skip scan would make 1,000 jumps. A dedicated index on created_at is still the better design. Check your server version with SELECT version(); before relying on skip scan.
Reuse: one index, several queries
An index on (customer_id, created_at) also serves queries that filter on customer_id alone, because the leading column is constrained:
EXPLAIN SELECT * FROM orders WHERE customer_id = 42;A separate index on (customer_id) is redundant. It costs write time and disk space and adds nothing. Before you add a single-column index, check whether an existing multicolumn index already has that column first.
The reverse does not hold. An index on (customer_id) cannot support WHERE customer_id = 42 ORDER BY created_at DESC LIMIT 20 without a sort, because the entries for one customer are not ordered by date.
Common mistakes
- Putting the range column first. It looks natural to lead with the date. The scan is then bounded only by the date range, and the equality column becomes a filter.
- Adding columns after a range column and expecting a narrower scan. In
(a, b)witha > 10 AND b = 3, thebtest happens inside the index, but the scan still covers every entry witha > 10. - Mixing up
INand ranges. A shortINlist on a leading column behaves like several equality probes, which is fine. A very long list, or a range, does not. - Judging by the index definition instead of the plan. Run
EXPLAIN (ANALYZE, BUFFERS). In the plan, look atIndex Condfor conditions that bound the scan, and atFilterandRows Removed by Filterfor conditions that did not.
Summary of the decision
For each important query, write down its equality columns, its range column, and its sort column. Build the index in that order: equality, then range or sort. Then check whether an existing index already covers the query as a prefix. Verify with EXPLAIN (ANALYZE, BUFFERS) that the scan is bounded the way you expect.
Exercise
A query is SELECT id FROM orders WHERE status = 'paid' AND customer_id = 7 AND created_at >= '2026-01-01' ORDER BY created_at. Which of these indexes serves it best, and why? (a) (created_at, status, customer_id) (b) (customer_id, status, created_at) (c) (created_at, customer_id)
Show answer
Index (b). Both customer_id and status use equality, so they go first in either order. created_at is the range and sort column, so it goes last. The scan is bounded to one block of entries for that customer and status, from the start date forward. The entries come out already in created_at order, so no sort step is needed. Options (a) and (c) lead with the range column, so the scan covers every order since January 1 and filters the other columns inside the index.
Exercise
You already have an index on (customer_id, created_at DESC). A colleague proposes adding CREATE INDEX ON orders (customer_id) to speed up WHERE customer_id = 42. Should you add it?
Show answer
No. The existing index has customer_id as its leading column, so it can bound the scan for a condition on customer_id alone. The new index would add storage and slow every insert and delete without making that query meaningfully faster. Confirm with EXPLAIN that the planner uses the existing index for the query.