Sub topic 8
Clustered and Secondary Indexes
This chapter assumes you know basic SQL, how a B+tree keeps entries in linked leaf pages, and why a lookup reads only a few pages. Here you will see what the leaf pages of an index actually hold, and why that changes the cost of a lookup.
Two ways to use the leaves
A B+tree leaf holds one entry per key. What sits next to the key decides the index type.
- A clustered index stores the full table row in the leaf. The table is the index, so rows are physically ordered by the clustering key.
- A secondary index stores the indexed columns plus a pointer to the row. The row lives somewhere else.
A table can have only one clustered index, because rows can be stored in only one order. It can have many secondary indexes.
What the pointer is
The pointer in a secondary index depends on the engine.
| Engine | Table storage | Secondary index leaf holds |
|---|---|---|
| InnoDB (MySQL) | Clustered on the primary key | The primary key value |
| PostgreSQL | Unordered heap file | A tuple ID (page number and slot in the heap) |
In InnoDB, a secondary lookup walks two trees. It searches the secondary index to get the primary key, then searches the clustered index with that key to get the row. In PostgreSQL, the tuple ID points straight into the heap, so the second step is one heap page read.
Worked example
Take the orders table from earlier chapters. Its primary key is id.
SELECT id, total
FROM orders
WHERE id = 42;In InnoDB, this is one tree descent. The leaf for id = 42 already contains total.
Now filter on a secondary column:
CREATE INDEX orders_customer_idx ON orders (customer_id);
SELECT id, total
FROM orders
WHERE customer_id = 7;The database descends the customer_id index and finds every entry for customer 7. For each match, it needs total, which is not in the index. So it follows the pointer to fetch the row. If customer 7 has 200 orders, that is up to 200 extra row fetches.
Why the extra fetch matters
The fetches can land on many different pages. Entries in the secondary index are sorted by customer_id, but the rows they point to are not stored in that order. Each fetch can be a random page read, which is far slower than reading neighboring pages in sequence.
This has two consequences:
- A secondary index is cheap when the query matches few rows. A few random fetches cost little.
- When the query matches a large share of the table, the planner often skips the index and scans the whole table instead. Sequential reads of everything can beat thousands of random reads.
Costs of each design
Clustering by primary key gives fast primary key lookups and fast range scans on that key, because neighboring keys sit on neighboring pages. It has a cost for writes. A random primary key, such as a random UUID, inserts rows at arbitrary places in the tree. That causes page splits throughout the table. An increasing key, such as a sequence, appends at the right edge.
In InnoDB, every secondary index entry stores the primary key. A wide primary key therefore makes every secondary index larger.
Updates matter too. If you change an indexed column, the database must update each index that contains it. In a heap-based engine like PostgreSQL, a changed row can get a new tuple ID, which may require new entries in indexes too. More secondary indexes mean slower writes.
Common errors
- Assuming PostgreSQL tables are clustered on the primary key. They are heaps, and the primary key index is a separate B-tree.
- Choosing a large or random primary key in InnoDB without considering the effect on page splits and secondary index size.
- Adding an index for every column. Each one slows inserts and updates and uses storage.
- Expecting a secondary index to be used for a query that returns most of the table.
Exercise
In InnoDB, a table has primary key id and a secondary index on email. A query runs SELECT name FROM users WHERE email = '[email protected]'. How many index trees does the database search, and why?
Show answer
Two. It searches the email secondary index first, which returns the primary key id for the match. Since name is not in that index, it then searches the clustered index using id and reads name from the full row in the leaf.
Exercise
Why can a planner choose a full table scan even though a secondary index exists on the filtered column?
Show answer
If the query matches a large fraction of rows, the index would require many random row fetches. A sequential scan of the whole table reads pages in order and can be cheaper than those random reads.