Sub topic 3
Multicolumn indexes
This chapter assumes you can read basic SELECT ... WHERE ... ORDER BY queries and know that an index speeds up lookups. You don't need to read EXPLAIN output fluently, but you should know how to run it. The chapter uses the orders and users tables from the running schema.
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()
);
CREATE TABLE users (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text NOT NULL,
deleted_at timestamptz
);What a multicolumn index is
A multicolumn index is a single B-tree built over two or more columns of one table. You list the columns in the CREATE INDEX statement, and the order you list them in is part of the index's definition.
CREATE INDEX orders_customer_status_idx
ON orders (customer_id, status);The index stores one entry per table row. Each entry holds the values of customer_id and status, plus a pointer to the row in the table. PostgreSQL sorts the entries by customer_id first. Entries with the same customer_id are then sorted by status. This is the same ordering as a phone book sorted by last name and then first name.
A B-tree supports up to 32 columns in one index. In practice, indexes with more than three or four columns are rare, because each extra column makes the index larger and more expensive to maintain.
How the search works
A B-tree search descends from the root page to a leaf page by comparing the search key against the keys stored on each page. With a multicolumn index, the search key can be a prefix of the columns, compared in order.
For WHERE customer_id = 42 AND status = 'paid', PostgreSQL descends to the first entry that is (42, 'paid'). It then reads forward through the leaf pages until the entries stop matching. All matching entries sit next to each other, so the scan reads a small contiguous slice of the index.
For WHERE customer_id = 42 alone, the matching entries still form one contiguous slice: every entry that starts with 42, whatever its status. The index helps here too.
For WHERE status = 'paid' alone, the matching entries are scattered. Each customer_id group holds its own 'paid' entries, and no single slice contains them all. The planner can still scan the whole index and filter, but that rarely beats a sequential table scan or a purpose-built index.
Seeing it in a plan
To run the examples yourself, load some test data and refresh the planner's statistics.
INSERT INTO orders (customer_id, status, total_cents, created_at)
SELECT (random() * 999)::bigint + 1,
(ARRAY['pending', 'paid', 'shipped', 'cancelled'])[1 + (random() * 3)::int],
(random() * 50000)::int,
now() - random() * interval '365 days'
FROM generate_series(1, 200000);
ANALYZE orders;Now check which queries use the index.
EXPLAIN
SELECT * FROM orders
WHERE customer_id = 42 AND status = 'paid';The exact numbers differ on your machine. The shape of the plan should look like this:
Bitmap Heap Scan on orders
Recheck Cond: ((customer_id = 42) AND (status = 'paid'::text))
-> Bitmap Index Scan on orders_customer_status_idx
Index Cond: ((customer_id = 42) AND (status = 'paid'::text))Both conditions appear under Index Cond. This means both were used to navigate the index. A plain Index Scan instead of a bitmap scan is also normal, depending on how many rows the planner expects.
Compare the second shape, where only the trailing column is constrained:
EXPLAIN
SELECT * FROM orders
WHERE status = 'paid';With 200,000 rows and about a quarter of them 'paid', the planner will almost certainly choose a Seq Scan. The index does not help much because the matching entries are spread across the whole index.
Equality columns and the first range column
Conditions fall into two groups, and they behave differently.
- Equality conditions (
=) on the leading columns narrow the scan to a contiguous slice. - The first inequality or range condition (
<,>,BETWEEN) on a column still narrows the slice, but it ends the narrowing. Conditions on columns to the right of it cannot shrink the range of entries the scan reads.
PostgreSQL's documentation puts it this way: equality constraints on leading columns, plus any inequality constraint on the first column without an equality constraint, are used to limit the portion of the index that is scanned. Conditions on the remaining columns are still checked against the index entries, which avoids visiting table rows that cannot match. They just don't reduce how much of the index is read.
Here is a concrete case:
CREATE INDEX orders_customer_created_idx
ON orders (customer_id, created_at DESC);
EXPLAIN
SELECT * FROM orders
WHERE customer_id = 42
AND created_at > now() - interval '30 days';The equality on customer_id picks out customer 42's entries. Within them, entries are ordered by created_at, so the range condition selects one contiguous part of that group. Both conditions narrow the scan.
Now reverse the column order in your head: an index on (created_at, customer_id). The range on created_at picks out a slice of the index, but inside that slice the customers are mixed together. The customer_id = 42 condition can be checked on each entry, but the scan still reads every entry in the date range. For a long date range that is much more work.
This is the reason column order matters. The next chapter covers how to choose it.
One multicolumn index or several single-column indexes?
PostgreSQL can combine separate single-column indexes. It scans each index, builds a bitmap of matching row locations from each, and combines the bitmaps with AND or OR (a BitmapAnd or BitmapOr node in the plan).
| Approach | Strengths | Weaknesses |
|---|---|---|
| One multicolumn index | Reads one narrow slice. Can supply sorted output. Can enforce uniqueness across the column combination. | Serves mainly queries that constrain its leading columns. |
| Several single-column indexes | Each index serves any query on its own column, in any combination. | Bitmap combination reads more entries and loses ordering. Total maintenance cost is higher. |
A multicolumn index is usually faster for the one query pattern it targets. Separate indexes are more flexible when you cannot predict which column combinations queries will use. Neither is a universal winner, so decide based on the queries you run most often.
Common errors
- Expecting every column to be searchable on its own. An index on
(customer_id, status)is not also an index onstatus. Queries that omitcustomer_idgenerally cannot use it efficiently. - Adding columns "just in case". Each column makes entries wider and the index bigger, and every
INSERTand mostUPDATEs must maintain it. Include a column only when a query benefits. - Creating an index that duplicates another. An index on
(customer_id)becomes redundant when(customer_id, created_at)exists, because the second serves the same lookups. Check for such overlaps before adding an index. - Reading the plan wrongly. A condition shown as
Filterrather thanIndex Condwas applied after rows were fetched from the table. Check where each condition appears.
Quick checks before you create one
- Write down the real queries the index should serve.
- List which columns each query compares with
=, which it compares with a range, and which it sorts by. - Create the index on a test copy with realistic data, run
ANALYZE, and checkEXPLAINforIndex Condentries. - Compare the plan and timing with and without the index before deploying.
Exercise
A table has the index CREATE INDEX t_idx ON t (a, b, c);. For each query, say whether the equality conditions narrow the index scan well: (1) WHERE a = 1 AND b = 2, (2) WHERE b = 2 AND c = 3, (3) WHERE a = 1 AND b > 5 AND c = 3.
Show answer
(1) Yes. Both conditions are on leading columns, so the scan reads one contiguous slice. (2) Not well. Column a is not constrained, so the matching entries are scattered across the index and the planner will likely choose another plan (on PostgreSQL 18, skip scan may help if a has few distinct values). (3) Partly. The equality on a and the range on b narrow the scan. The condition on c is checked against each entry in that range but does not shrink the range, because it comes after the first range column.
Exercise
You have orders_customer_created_idx on (customer_id, created_at DESC). Which of these queries should use it efficiently: WHERE customer_id = 7, or WHERE created_at > now() - interval '1 day'? Explain why.
Show answer
The first one. It constrains the leading column customer_id, so the matching entries are contiguous. The second constrains only created_at, the second column, so the matching entries are spread across every customer's group and the index does not narrow the scan well. It usually needs an index that starts with created_at.