Sub topic 4
Multicolumn, Partial, Expression, and Covering B-tree Indexes
This chapter assumes you can read basic EXPLAIN output, as covered in the earlier chapters on the planner and on B-trees. It also assumes you know that a B-tree stores keys in sorted order and can answer =, <, >, BETWEEN, and ORDER BY requests. Here you will see four ways to shape a B-tree so it matches a specific query: more than one column, a subset of rows, a computed value, or extra payload columns.
Multicolumn indexes
A multicolumn index sorts entries by the first column, then by the second column within equal first values, and so on. It behaves like a phone book sorted by last name, then first name.
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id bigint NOT NULL,
status text NOT NULL,
total numeric(10,2),
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX orders_customer_created_idx
ON orders (customer_id, created_at DESC);
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, total
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 10;The planner can descend the tree to the first entry for customer_id = 42. Entries for that customer are already sorted by created_at DESC, so it reads ten entries and stops. No Sort node appears in the plan, and the LIMIT ends the scan early.
Column order decides what the index can do
The usable part of a multicolumn B-tree is determined by the leading columns. Follow these rules when you choose the order:
- Conditions with
=on leading columns narrow the scan to one contiguous slice of the index. - The first column with a range condition (
<,>,BETWEEN) also narrows the scan. Conditions on columns after it are checked against each entry in that range but do not make the scanned range smaller. - A condition only on a later column, such as
WHERE created_at > ...against(customer_id, created_at), cannot narrow the scan. The planner may still read the whole index, which is usually slower than a well-matched index. PostgreSQL 18 added skip scan, which helps when the leading column has few distinct values. Older versions do not have it.
As a rule of thumb, put equality columns first and the range or sort column last.
| Query shape | Index `(customer_id, created_at)` helps? |
|---|---|
| `WHERE customer_id = 42` | Yes, uses the leading column |
| `WHERE customer_id = 42 AND created_at > '2026-01-01'` | Yes, uses both columns |
| `WHERE customer_id = 42 ORDER BY created_at` | Yes, no sort needed |
| `WHERE created_at > '2026-01-01'` | Poorly, no narrowing on the leading column |
Sort direction
An index can satisfy ORDER BY only if the requested order matches the index order or its exact reverse. The index above, (customer_id, created_at DESC), serves both ORDER BY customer_id, created_at DESC and ORDER BY customer_id DESC, created_at, because the second is the full reverse and the scan can run backward. It does not serve ORDER BY customer_id, created_at ASC. That query needs an index declared (customer_id, created_at). When one column is fixed by an equality condition, as in the example query, the direction of that column does not matter.
One multicolumn index versus two single-column indexes
PostgreSQL can combine separate indexes with a bitmap AND. This works, but it reads two indexes, builds bitmaps in memory, and loses ordering. It cannot deliver rows in created_at order, so ORDER BY ... LIMIT queries still need a sort. For a query shape you run often, one multicolumn index is usually faster. For many different filter combinations, single-column indexes combined by bitmaps may be the better trade.
A multicolumn B-tree can have up to 32 columns, but wide indexes are larger and slower to maintain. Past three or four columns, check that each one pays for itself.
Partial indexes
A partial index contains entries only for rows that satisfy a WHERE predicate. It is smaller, cheaper to update, and more likely to stay in memory.
CREATE INDEX orders_open_created_idx
ON orders (created_at)
WHERE status = 'open';
EXPLAIN (ANALYZE, BUFFERS)
SELECT id
FROM orders
WHERE status = 'open'
AND created_at < now() - interval '7 days'
ORDER BY created_at
LIMIT 20;If 2% of orders are open, this index is about 2% of the size of a full index on created_at. Inserts and updates of rows that are not open do not touch it at all.
When the planner will use it
The planner may use a partial index only if it can prove that the query's WHERE clause implies the index predicate. The proof is simple pattern matching, not general reasoning:
status = 'open'in the query matches the predicatestatus = 'open'.- A query on
status = $1with an unknown parameter does not match. This matters for prepared statements. PostgreSQL normally picks a custom plan with the actual value for the first several executions, and that plan can use the index. If it switches to a generic plan, the index becomes unusable. Checkplan_cache_modeif you see this. - A query that omits the predicate cannot use the index, even if every row it would return happens to be open.
Partial unique indexes
Partial indexes can enforce rules that apply to only some rows. The following allows a deleted user's email to be reused while keeping active emails unique:
CREATE TABLE users (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text NOT NULL,
deleted_at timestamptz
);
CREATE UNIQUE INDEX users_active_email_idx
ON users (lower(email))
WHERE deleted_at IS NULL;This index is both a partial index and an expression index, which the next section covers.
Expression indexes
An expression index stores the result of a computation instead of a raw column value. Use it when queries filter or sort on that computation.
CREATE INDEX users_lower_email_idx
ON users (lower(email));
SELECT id FROM users WHERE lower(email) = '[email protected]';Without this index, WHERE lower(email) = ... cannot use a plain index on email, because the stored values are not lowercased. The planner would scan the whole table.
The query must repeat the expression
The planner matches expressions structurally. An index on lower(email) does not help WHERE email ILIKE '[email protected]', and an index on (a + b) does not help WHERE b + a = 5. Write queries with exactly the indexed expression.
Syntax and immutability
A single function call can be written directly in the column list, as above. Any other expression needs its own parentheses, which gives the double parentheses you see below:
CREATE INDEX orders_created_day_idx
ON orders (((created_at AT TIME ZONE 'UTC')::date));
SELECT count(*)
FROM orders
WHERE (created_at AT TIME ZONE 'UTC')::date = DATE '2026-11-01';Every function in an index expression must be immutable, meaning the same inputs always give the same output. date_trunc('day', created_at) on a timestamptz column is only stable, because the result depends on the session time zone. PostgreSQL rejects it with an error. Converting with a fixed zone, as above, is immutable.
Statistics follow the expression
ANALYZE collects statistics on index expressions, so the planner can estimate how many rows lower(email) = '...' will return. Expression indexes cost more to maintain, because the function runs on every insert and on every update that changes an input column.
Covering indexes with INCLUDE
Normally an index entry holds only the key columns and a pointer to the table row (the heap). After finding an entry, PostgreSQL visits the heap to fetch other columns. An index-only scan skips that visit when the index holds every column the query needs.
CREATE INDEX orders_customer_incl_idx
ON orders (customer_id) INCLUDE (total);
VACUUM (ANALYZE) orders;
EXPLAIN (ANALYZE, BUFFERS)
SELECT customer_id, total
FROM orders
WHERE customer_id = 42;INCLUDE columns are stored in the index entry but are not part of the sort key. You can include columns of any type, even ones without a B-tree ordering, and including a column does not constrain how the tree is built.
Reading the plan
Look for Index Only Scan and the line Heap Fetches: N. An index-only scan still checks whether each row is visible to your transaction. It does this with the table's visibility map, which records pages where all rows are visible to everyone. If a page is not marked all-visible, PostgreSQL must visit the heap, and that visit is counted in Heap Fetches. Pages become all-visible through VACUUM. On a table with many recent updates, an index-only scan may read the heap almost as often as a normal index scan.
Key column or INCLUDE column?
Put a column in the key if queries filter or sort on it. Put it in INCLUDE if you only read it. An INCLUDE column cannot be used to narrow the scan or provide ordering. It also does not take part in uniqueness checks:
CREATE UNIQUE INDEX orders_id_incl_idx
ON orders (id) INCLUDE (customer_id);This enforces uniqueness on id only. If customer_id were a key column, the pair (id, customer_id) would have to be unique, which is a different rule.
Index entries have a size limit of roughly one third of a page, around 2700 bytes with the default 8 kB pages. Including a long text column can hit that limit and make inserts fail.
Combining the techniques
The variants compose. This index serves a dashboard query for old open orders per customer. It is partial (open orders only), multicolumn (customer then age), and covering (the total is available without the heap):
CREATE INDEX orders_open_customer_idx
ON orders (customer_id, created_at)
INCLUDE (total)
WHERE status = 'open';Each added feature narrows the set of queries that can use the index. A highly specific index is fast for its query and useless for others, and every index adds write cost. Build one for a query that matters, not for every query.
Common mistakes
- Wrong column order. An index on
(created_at, customer_id)does not serveWHERE customer_id = 42 ORDER BY created_at DESC LIMIT 10as well as(customer_id, created_at DESC). Put equality columns first. - Redundant indexes. An index on
(customer_id, created_at)already serves queries oncustomer_idalone, so a separate index oncustomer_idis usually dead weight. - Expression mismatch. Indexing
lower(email)and queryingemail ILIKE ...leaves the index unused. - Partial index never matches. The query must contain a condition that implies the predicate, and parameterized generic plans cannot prove it.
- Index-only scans that are not. With heavy writes and infrequent vacuum,
Heap Fetchesstays high. Check autovacuum settings before blaming the index. - Oversized INCLUDE lists. Including many or wide columns makes the index nearly as large as the table and slows writes.
Exercise
A table tickets(id, team_id, status, priority, created_at) is queried constantly with WHERE team_id = $1 AND status = 'open' ORDER BY created_at DESC LIMIT 25. Only about 3% of tickets are open. Write one index that supports this query with no sort step and keeps the index small, then explain the column order.
Show answer
CREATE INDEX ticketsopenteamcreatedidx ON tickets (teamid, createdat DESC) WHERE status = 'open'; The equality column teamid comes first, and createdat DESC comes next so rows for one team are already in the requested order and the LIMIT can stop early. The partial predicate status = 'open' removes the 97% of rows the query never reads, which shrinks the index and skips maintenance for non-open tickets. The query's literal 'open' lets the planner prove it implies the predicate.
Exercise
You created CREATE INDEX ON users (lower(email));. Which of these queries can use it: (a) WHERE lower(email) = '[email protected]', (b) WHERE email = '[email protected]', (c) WHERE upper(email) = '[email protected]'? Why?
Show answer
Only (a). The planner matches the indexed expression exactly. The index stores lower(email) values, not raw email values, so (b) cannot use it, and upper(email) in (c) is a different expression whose values are not in the index.
Exercise
An index ON orders (customer_id) INCLUDE (total) exists, and the plan for SELECT customer_id, total FROM orders WHERE customer_id = 42 shows Index Only Scan with Heap Fetches: 9800 for about 10000 rows. What is the likely cause and the fix?
Show answer
Most pages are not marked all-visible in the visibility map, usually because the table has had many recent updates or deletes and has not been vacuumed. The scan must visit the heap to check row visibility. Run VACUUM on the table (and tune autovacuum so it runs often enough), then re-check that Heap Fetches drops toward 0.