B-Tree index internals and composite index column order
How B-Tree page layout, the leftmost prefix rule, equality vs. range column order, and covering indexes work in PostgreSQL 15 and MySQL 8.0.
Putting “frequently queried columns first” isn’t enough to make a composite index work. This post walks through B-Tree page ordering, the leftmost prefix rule, equality-before-range column placement, and covering indexes in PostgreSQL and InnoDB.
Tested with PostgreSQL 15.4 and MySQL 8.0.34 (InnoDB). All execution plans were verified against 1 million dummy rows in local Docker containers.
Background
During a database course team project, I built a small order management service and added a composite index on orders(created_at, user_id) to speed up the “recent orders for a user” query. When I checked the execution plan, the database did pick the index—yet it still scanned hundreds of thousands of index entries on every request. Flipping the column order to (user_id, created_at) dropped the number of buffer reads from thousands of pages down to single digits.
That mistake changed how I think about indexes. A B-Tree index isn’t a magic lookup accelerator; it’s a sorted data structure, and query performance comes down to how far your WHERE and ORDER BY clauses can follow that sort order.
How B-Tree indexes work under the hood
A B-Tree index is a balanced tree made up of root, branch, and leaf pages. Leaf pages store index keys in sorted order and link to neighboring leaves via doubly linked pointers, so a range scan walks sideways across adjacent pages without climbing back up the tree. Because the tree height typically stays at 3 to 4 levels even on tables with millions of rows, finding a single key takes only a handful of page reads.
flowchart TD
A["Root page"] --> B["Branch page"]
B --> C["Leaf page (sorted keys)"]
C --> D{"Storage engine"}
D -->|"PostgreSQL"| E["Fetch heap tuple by TID"]
D -->|"InnoDB"| F["Re-lookup clustered index by PK"]
One layer deeper, PostgreSQL and InnoDB store different pointers in their leaf pages, and that difference shapes how covering indexes and random I/O behave:
- PostgreSQL: Table data lives in an unordered heap. Each index leaf entry holds
(key, TID), where the Tuple Identifier (TID) is a(block number, offset)pair that jumps straight to the physical heap page. Pages are 8KB, and since PostgreSQL 13, B-Tree deduplication packs duplicate keys into posting lists to shrink index size. - InnoDB: The table itself is a clustered index ordered by the primary key. Secondary index leaf entries store
(key, PK value)instead of a physical row pointer. If a query needs columns outside the index, InnoDB performs a second lookup into the clustered index using that PK. The default page size is 16KB.
A composite index on (a, b, c) sorts entries by a first, then by b within equal values of a, and finally by c within equal values of (a, b). It works just like a printed phone book sorted by last name and then first name. If you only know someone’s first name, you can’t jump to the right page—you have to flip through the entire book. Without a condition on the leading column, the database can’t narrow the B-Tree search range. That constraint is the leftmost prefix rule.
Column order rules and trade-offs
Here is how a (a, b, c) composite index behaves across common query patterns:
| Query predicate | How (a, b, c) is used | Behavior |
|---|---|---|
a = ? AND b = ? AND c = ? | All three columns narrow the search | Best case; direct range lookup |
a = ? AND b > ? AND c = ? | a and b narrow the search; c is filtered | Range predicate on b breaks sort order for c |
b = ? AND c = ? | Leading column missing | Full index/table scan in PostgreSQL; conditional skip scan in MySQL 8.0.13+ |
a = ? ORDER BY b | Sort step eliminated | Leaf order already matches ORDER BY |
a IN (?, ?) AND b = ? | Multiple narrow range lookups | Effective when the IN list is short |
From this layout, I apply three ordering rules when designing a composite index:
- Place equality columns before range columns. For
WHERE a = ? AND b BETWEEN ...,(a, b)lets the engine jump directly toaand scan only the matching slice ofb. Reversing it to(b, a)forces the engine to scan every entry in thebrange and filterarow by row. - Use selectivity as a tiebreaker among equality columns. Putting a high-selectivity column (more distinct values) earlier generally narrows the search faster. In practice, though, whether other queries filter on the leading column alone matters more than raw cardinality, so I check query coverage first and use selectivity to break ties.
- Include the
ORDER BYcolumn forLIMITqueries. When a list endpoint filters onuser_idand sorts bycreated_at DESC LIMIT 20, placingcreated_atright afteruser_idlets the engine read 20 entries in reverse order and stop immediately without sorting.
A covering index takes this one step further by containing every column the query selects, eliminating table lookups altogether. PostgreSQL reports this as an Index Only Scan, while MySQL shows Extra: Using index. Since PostgreSQL 11, you can use the INCLUDE clause to attach non-key payload columns to leaf pages without paying the cost of keeping them in branch pages or sorting on them.
When not to add composite indexes: On write-heavy tables, adding a dedicated composite index for every query shape slows down INSERT and UPDATE operations because every index must be maintained on each write, and it bloats disk and buffer cache usage. Creating a standalone index on a low-cardinality column like a boolean flag or a two-value status rarely pays off either—the planner will usually choose a sequential scan anyway. Also watch out for redundant prefixes: if you already have (a, b), a separate index on (a) is almost always dead weight and can be dropped.
Verifying with execution plans
You can reproduce the exact before-and-after difference locally in PostgreSQL 15 with 1 million rows:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
-- PostgreSQL 15
CREATE TABLE orders (
id bigserial PRIMARY KEY,
user_id bigint NOT NULL,
status varchar(20) NOT NULL,
created_at timestamptz NOT NULL
);
INSERT INTO orders (user_id, status, created_at)
SELECT (random() * 10000)::bigint,
(ARRAY['PAID', 'SHIPPED', 'CANCELED'])[1 + (random() * 2)::int],
now() - (random() * interval '365 days')
FROM generate_series(1, 1000000);
CREATE INDEX idx_orders_created_user ON orders (created_at, user_id);
ANALYZE orders;
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, created_at FROM orders
WHERE user_id = 42 AND created_at >= now() - interval '30 days'
ORDER BY created_at DESC LIMIT 20;
-- Flip the column order and include id for a covering scan
DROP INDEX idx_orders_created_user;
CREATE INDEX idx_orders_user_created ON orders (user_id, created_at) INCLUDE (id);
VACUUM ANALYZE orders; -- Refresh the visibility map to enable Index Only Scan
With the first index (created_at, user_id), Index Cond still lists both predicates, which can fool you at a glance. Look closer at Buffers: shared hit: only the leading column created_at narrows the B-Tree range, so PostgreSQL scans every order from the last 30 days and checks user_id = 42 entry by entry. After switching to (user_id, created_at) INCLUDE (id) and refreshing the visibility map, the plan switches to Index Only Scan Backward and buffer reads drop to single digits. I wrote up a fuller breakdown of reading these numbers in Reading PostgreSQL EXPLAIN ANALYZE execution plans.
In MySQL 8.0, you can inspect the same query using EXPLAIN FORMAT=TREE or EXPLAIN ANALYZE (available since 8.0.18):
1
2
3
4
5
6
-- MySQL 8.0
CREATE INDEX idx_orders_user_created ON orders (user_id, created_at);
EXPLAIN FORMAT=TREE
SELECT id, created_at FROM orders
WHERE user_id = 42 AND created_at >= NOW() - INTERVAL 30 DAY
ORDER BY created_at DESC LIMIT 20;
Because InnoDB automatically appends the primary key (id) to every secondary index leaf entry, (user_id, created_at) is already a covering index for SELECT id, created_at—you don’t need an INCLUDE clause.
Production pitfalls and checklist
Wrapping an indexed column in a function or triggering an implicit type cast—such as
WHERE date(created_at) = ...or comparing avarcharcolumn to an integer—prevents the database from using the B-Tree’s sort order and forces a full scan. Also remember that PostgreSQL’sIndex Only Scanskips heap access only for pages marked all-visible in the visibility map. On heavily updated tables, a highHeap Fetchescount means the scan is still hitting the heap frequently.
Designing a composite index comes down to asking how far a query can walk along the B-Tree’s sorted leaf pages. Before creating a new index, I run through this checklist:
- Are equality predicate columns placed ahead of range predicate columns?
- Do any other queries need to filter without the leading column?
- Does the index order match the
ORDER BY ... LIMITsort order? - Does the new index duplicate the prefix of an existing index?
- Did
EXPLAIN (ANALYZE, BUFFERS)confirm that buffer reads actually dropped?