Sub topic 7
Composite indexes and the leftmost-prefix rule
This chapter assumes you can read basic EXPLAIN output and know that a B-tree keeps its keys in sorted order. It also assumes you know the difference between a point lookup and a range scan. Examples use PostgreSQL syntax, and the same ideas apply to MySQL and most other B-tree databases.
What a composite index is
A composite index (also called a multicolumn index) is a single B-tree built on more than one column. The entries are sorted by the first column. Entries with equal first values are sorted by the second column, and so on.
Think of a phone book sorted by last name, then first name. Finding "Smith, Jordan" is fast. Finding every "Jordan" is not, because the Jordans are scattered under every last name.
CREATE INDEX orders_customer_created_idx
ON orders (customer_id, created_at);For this index, the leaf entries look like this:
| customer_id | created_at | points to row |
|---|---|---|
| 41 | 2026-03-02 | row A |
| 42 | 2026-01-05 | row B |
| 42 | 2026-02-11 | row C |
| 42 | 2026-04-30 | row D |
| 43 | 2026-01-01 | row E |
Rows for customer 42 sit next to each other and are ordered by created_at. Rows with created_at in January are spread across the whole index.
The leftmost-prefix rule
An index on (a, b, c) can be searched efficiently by these column sets:
aa, ba, b, c
It cannot be seeked efficiently using b, c, or b, c alone. The usable columns are a prefix of the index definition, starting from the left.
-- Can use the index: leading column is constrained.
SELECT * FROM orders
WHERE customer_id = 42 AND created_at >= '2026-01-01';
-- Cannot use it efficiently for a seek: the leading column is missing.
SELECT * FROM orders
WHERE created_at >= '2026-01-01';The first query descends the tree to the first entry for customer 42 on or after January 1. It then reads forward until the customer changes. The second query has no single place to descend to, because matching entries are scattered across every customer.
Equality first, then one range
The index can narrow the search in a clean way only while the conditions on the leading columns are equalities. The first column constrained by a range (>, <, BETWEEN) ends the useful narrowing. Columns after it can still be checked, but only by scanning entries inside the range.
Take an index on (customer_id, created_at, status):
| Query condition | How the index is used |
|---|---|
| `customer_id = 42` | Seek on `customer_id` |
| `customer_id = 42 AND created_at >= '2026-01-01'` | Seek on both columns |
| `customer_id = 42 AND created_at >= '2026-01-01' AND status = 'open'` | Seek on the first two. `status` is filtered while scanning the range |
| `customer_id = 42 AND status = 'open'` | Seek on `customer_id`. `status` is filtered across all of customer 42's entries |
| `created_at >= '2026-01-01'` | No efficient seek |
Some planners can do better than this table suggests. PostgreSQL can use a non-leading column as an index condition, though it scans much more of the index. MySQL 8.0 can do a "skip scan" when the leading column has few distinct values. Treat these as optimizations you may get, not behavior to design around.
Column order decides which queries benefit
Because only prefixes are searchable, the order of columns is a design decision. Compare these two indexes:
CREATE INDEX idx_a ON orders (customer_id, created_at);
CREATE INDEX idx_b ON orders (created_at, customer_id);Consider the queries each one serves:
| Query | `idx_a` | `idx_b` |
|---|---|---|
| `WHERE customer_id = 42` | Good seek | Poor, no leading column |
| `WHERE customer_id = 42 AND created_at >= X` | Good seek, tight range | Seek on `created_at`, then filter on `customer_id` over a wide range |
| `WHERE created_at >= X` | Poor | Good seek |
The second row matters most. With idx_b, the index reads every entry in the date range, from all customers, and tests each for customer_id = 42. With idx_a, it reads only customer 42's entries. When one condition is an equality and the other a range, put the equality column first.
A practical ordering heuristic:
- Put columns compared with
=first. - Among those, put the more frequently queried column first, so shorter prefixes are useful to more queries.
- Put the range column, or the column used for
ORDER BY, after the equality columns.
Selectivity (how few rows a value matches) matters, but it is not the main rule. A low-selectivity column such as status can still be the best first column if every query filters on it by equality and you also need the ordering of the next column.
Composite indexes and sort order
Because entries are stored in order, a composite index can also satisfy ORDER BY without a separate sort step.
SELECT id, created_at
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 10;With (customer_id, created_at), the database descends to customer 42 and walks the index backward. It stops after 10 entries. No sort is needed, and it never reads the other rows for that customer.
This works only because customer_id is pinned to one value. Within a single customer, the entries are already in created_at order. If you filtered with customer_id IN (1, 2), the entries for the two customers would come back as two separate sorted runs, and the planner would need to merge or sort them.
Direction matters when you mix directions. An index on (a, b) can serve ORDER BY a, b and ORDER BY a DESC, b DESC by reading forward or backward. It cannot serve ORDER BY a ASC, b DESC unless you declare the index that way:
CREATE INDEX orders_mixed_idx
ON orders (customer_id ASC, created_at DESC);Composite index versus several single-column indexes
Two separate indexes, one on customer_id and one on created_at, are not equivalent to one composite index. PostgreSQL can combine them with a bitmap AND, which builds a set of matching row locations from each index and intersects them. This is often slower than one composite seek, and it cannot provide ordering. A composite index is usually better for a query that always filters on both columns. Separate indexes are more flexible when queries filter on either column independently.
Redundant indexes
An index on (a, b) already serves every query that an index on (a) alone would serve. The single-column index adds write and storage cost with little benefit, so you can usually drop it. There is one exception: the narrower index is smaller, so scans over it touch fewer pages. This rarely justifies keeping it.
An index on (b) is not redundant with (a, b), because b is not a prefix.
Verifying with EXPLAIN
Do not assume the planner uses the index. Check it.
EXPLAIN
SELECT * FROM orders
WHERE customer_id = 42 AND created_at >= '2026-01-01';A plan that uses the index shows a line such as Index Scan using orders_customer_created_idx on orders with an Index Cond listing both columns. If you see only customer_id in Index Cond and created_at in a separate Filter line, the second column was not used as a seek condition. A Seq Scan means the planner decided not to use the index at all, often because the query matches a large share of the table.
Common errors
- Reversed column order. Putting the range column before the equality column forces the index to scan a wide range.
- Assuming any column of the index helps. Only a leading prefix narrows the search.
- Skipping a middle column. With
(a, b, c)and a query onaandc, the index narrows onaonly.cis filtered afterward. - Adding columns "just in case". Each extra column makes the index larger and every write slower.
- Keeping redundant prefixes.
(a)next to(a, b)is usually wasted.
Exercise
A table has an index on (status, customerid, createdat). For each query, say how many of the leading columns the index can use for seeking: (1) WHERE status = 'open' AND customerid = 7; (2) WHERE customerid = 7 AND createdat >= '2026-01-01'; (3) WHERE status = 'open' AND createdat >= '2026-01-01'.
Show answer
(1) Two columns, status and customerid, both equalities in the leading prefix. (2) None for an efficient seek, because status, the leading column, is missing. (3) One column, status. The index cannot seek on createdat because customerid, which sits between them, is not constrained, so createdat is only filtered afterward.
Exercise
Queries on an events table always filter with userid = ? and a time range on occurredat, and sometimes also read results ordered by occurredat. Which index should you create, (userid, occurredat) or (occurredat, user_id), and why?
Show answer
Create (userid, occurredat). The equality column comes first, so the index narrows to one user's entries, which are already sorted by occurredat. This handles the range and the ordering together. With the reverse order, the index would scan the whole time range across all users and filter by userid.