Sub topic 9
Clustered and Secondary Indexes
This chapter assumes you know what a B-tree index is, how a point lookup walks from root to leaf, and how to read basic EXPLAIN output. It covers how a table's rows relate to its indexes. That relationship decides how many steps a lookup takes and how much an index costs to maintain.
Two ways to store a table
A B-tree index maps key values to rows. The open question is where the full row lives. Databases answer it in one of two ways.
- Clustered (index-organized) storage. The table's rows are stored inside the leaves of a B-tree, ordered by one key. The table is the index. Each table can have only one such ordering.
- Heap storage. Rows sit in an unordered collection of pages called the heap. Every index, including the primary key index, is a separate structure that points into the heap.
An index that does not hold the full row is a secondary index. In a clustered engine, a secondary index points to the row by its clustering key. In a heap engine, it points to a physical location.
| Engine | Row storage | Secondary index leaf holds |
|---|---|---|
| MySQL InnoDB | Clustered on the primary key | Indexed columns plus the primary key value |
| SQL Server | Clustered if a clustered index exists, otherwise heap | Indexed columns plus the clustering key (or a row locator for a heap) |
| PostgreSQL | Heap | Indexed columns plus a tuple ID (TID) |
| SQLite (rowid tables) | Clustered on `rowid` | Indexed columns plus the rowid |
The examples in this tutorial use PostgreSQL, so the orders table is a heap. Its primary key index on id is already a secondary index in the sense used here.
Clustered indexes
In a clustered layout the leaf level of the primary key B-tree contains complete rows. Finding a row by primary key takes one root-to-leaf walk, and the walk ends at the data. No second fetch is needed.
Rows with adjacent key values are also adjacent on disk. A range scan on the clustering key reads consecutive leaf pages, which is cheap sequential-style I/O.
This has consequences for the choice of key:
- Insert order matters. With an increasing key such as an auto-increment
id, new rows append to the rightmost leaf. With a random key such as a UUIDv4, inserts land in arbitrary leaves. This causes page splits and scattered writes. - Key size matters. Every secondary index entry in a clustered engine carries a copy of the clustering key. A wide primary key makes every secondary index larger.
- Updating the key is expensive. Changing a clustering key value moves the row to a different leaf position, and every secondary index entry for that row must change too.
Secondary indexes
A secondary index is a separate B-tree sorted by its own key columns. Its leaf entries contain the indexed values plus a reference to the row. The reference is the primary key in a clustered engine or a TID in PostgreSQL.
Take the index from the earlier chapters:
CREATE INDEX orders_customer_id_idx ON orders (customer_id);
EXPLAIN SELECT * FROM orders WHERE customer_id = 42;Running the query takes two phases. First the engine walks the secondary index to find entries with customer_id = 42. Then, for each match, it fetches the row. That second step is called a lookup (InnoDB, SQL Server key lookup) or a heap fetch (PostgreSQL). It is a random read into a different structure.
The cost of those fetches is why an index with low selectivity can lose to a sequential scan. If 40% of the rows match, the engine would do millions of random fetches where a single sequential pass is cheaper. The planner weighs this using its statistics.
Heap fetches in PostgreSQL
In PostgreSQL the index entry contains a TID, a pair of (page number, slot within the page). The fetch goes straight to that page without another tree walk. This is cheaper per row than a second B-tree descent, but it has its own behavior.
Because the heap is unordered, rows matching one index key can be scattered across many pages. A plain Index Scan fetches each row as it reads the index entry, which may revisit the same page many times. A Bitmap Heap Scan first collects all matching TIDs, sorts them by page, and then visits each page once. The planner often picks the bitmap form for mid-sized result sets.
PostgreSQL also has the CLUSTER command. It rewrites the table once in the order of an index. This is a one-time reorder, not a maintained property. New rows go wherever there is space, and the order decays. The planner tracks how well heap order matches an index through a statistic called correlation, which you can see in pg_stats.
SELECT attname, correlation
FROM pg_stats
WHERE tablename = 'orders' AND attname IN ('id', 'customer_id', 'created_at');A correlation near 1 or -1 means the physical row order follows that column. Range scans on such a column need few page visits. Near 0 means matching rows are scattered.
The extra hop and how to avoid it
If a secondary index contains every column the query needs, the engine never visits the row. This is a covering index, covered in the next chapters. In a clustered engine, the secondary index implicitly includes the primary key, so a query that selects only indexed columns and the primary key is already covered:
-- MySQL InnoDB: id is carried inside every secondary index entry,
-- so this is answered from the index alone.
SELECT id, customer_id FROM orders WHERE customer_id = 42;In PostgreSQL the same idea requires the columns to be in the index (using INCLUDE if needed), and the visibility map must show the pages as all-visible.
Choosing a clustering key
When the engine lets you choose, use these criteria:
- Narrow. Its size is copied into every secondary index.
- Unique and stable. Rarely updated, and never reused.
- Ever-increasing, unless you have a reason otherwise. This keeps inserts at the right edge of the tree.
- Matches the dominant range access. If most queries read contiguous slices, such as time-series data by timestamp, clustering on that column can help.
In InnoDB the clustering key is the primary key. If you define none, it uses the first unique non-null index, or a hidden row ID. A surrogate integer key is a safe default. A natural wide key, such as a long string, inflates every other index.
SQL Server separates the two ideas. A primary key is nonclustered if you declare it that way, and you can cluster on another column.
Common mistakes
- Assuming PostgreSQL clusters on the primary key. It does not. The primary key index is a separate B-tree over a heap.
- Using random UUIDs as an InnoDB primary key. This fragments the clustered tree and bloats every secondary index with 16-byte (or 36-byte, if stored as text) keys. Time-ordered UUIDs (such as UUIDv7) avoid the random insert pattern.
- Adding many secondary indexes to a table with a wide clustering key. Each one repeats the key.
- Expecting
CLUSTERin PostgreSQL to stay in effect. It holds a lock while it runs and must be repeated.
Summary of trade-offs
| Property | Clustered storage | Heap storage |
|---|---|---|
| Primary key lookup | One tree walk | One tree walk plus one page fetch |
| Secondary lookup | Two tree walks | One tree walk plus one page fetch |
| Range scan on the key | Sequential leaf reads | Scattered fetches unless correlated |
| Insert with random key | Page splits in the table itself | Appends to the heap, but the index still splits |
| Secondary index size | Grows with the clustering key | Fixed-size TID |
Exercise
A MySQL InnoDB table has PRIMARY KEY (id) where id is a CHAR(36) UUID string, and five secondary indexes. Name two costs this design adds compared with a BIGINT auto-increment key, and one way to reduce them.
Show answer
First, every secondary index entry stores a copy of the 36-byte primary key, so all five indexes are larger and fewer entries fit per page. Second, random UUID inserts land in arbitrary leaves of the clustered tree, causing page splits and poor cache locality. To reduce the cost, use a BIGINT surrogate key, or store the UUID as BINARY(16) and use a time-ordered variant such as UUIDv7.
Exercise
In PostgreSQL, SELECT * FROM orders WHERE customer_id = 42 uses orders_customer_id_idx and returns 5,000 rows. Why might the plan show a Bitmap Heap Scan rather than a plain Index Scan, and what does the correlation value for customer_id tell you?
Show answer
The matching rows are probably scattered across many heap pages. A bitmap scan collects the TIDs, sorts them by page, and reads each page once instead of revisiting pages in index order. A correlation near 0 means the physical row order does not follow customer_id, which is why the planner favors the bitmap form. A value near 1 or -1 would make a plain Index Scan cheaper.