Heap vs clustered index: PostgreSQL and MySQL side by side
One question, two answers
The last two articles asked the same question of two databases: when you insert a row, where does it go?
- In PostgreSQL, it goes into the heap, on any page that has room. Every index is a separate structure that points into the heap.
- In MySQL’s InnoDB, it goes into the clustered index: the leaf page of the primary key’s B+ tree where its key belongs. Every other index points at the primary key.
This article puts the two next to each other and follows that one difference through every operation. It does not pick a winner. Each design is cheap where the other is expensive, and the useful thing to know is which is which.
“Heap” and “clustered index” are industry terms for the two layouts, as both earlier articles explain. Everything below is about PostgreSQL’s and InnoDB’s own versions of them.
What this article builds on
This is the sixth article in the series, and it uses something from each of the others:
| Article | What this one takes from it |
|---|---|
| Binary search | How both databases find a key inside one page |
| B-trees | Pages as nodes, fan-out, and how nodes split and merge |
| B+ trees | Entries only in the leaves, linked leaves, and range scans along them |
| The PostgreSQL heap | TIDs, tuple versions, HOT updates, VACUUM and the visibility map |
| The MySQL clustered index | Rows in the primary key’s leaves, the two hidden columns, the undo log and purge |
If a term below is unfamiliar, the link next to it leads to the section that introduces it.
The same table in both
The widget holds one accounts table twice: once as PostgreSQL stores it and once as InnoDB stores it. Both have a primary key on id and a second index on owner. Every operation runs on PostgreSQL first and then on InnoDB, and ends with one line that compares the two.
Press Insert to add a row. Pick a row and find it by id or by owner. Update its balance, which no index contains, and then its owner, which one index does. Delete it, then run VACUUM / purge. Under each engine, a line counts the work that operation cost. Turn Autoplay off to move with Next step instead, and use full screen to see both engines side by side.
PostgreSQL
| id | TID |
|---|---|
| 1 | (0,1) |
| 2 | (0,2) |
| 3 | (0,3) |
| owner | TID |
|---|---|
| atom eve | (0,1) |
| invincible | (0,2) |
| omni-man | (0,3) |
| lp | xmin | xmax | t_ctid | id | owner | balance | state |
|---|---|---|---|---|---|---|---|
| 1 | 750 | 0 | (0,1) | 1 | atom eve | 100 | live |
| 2 | 750 | 0 | (0,2) | 2 | invincible | 200 | live |
| 3 | 750 | 0 | (0,3) | 3 | omni-man | 300 | live |
MySQL (InnoDB)
No separate primary key index. PRIMARY is that index and the table at once.
| owner | id | state |
|---|---|---|
| atom eve | 1 | live |
| invincible | 2 | live |
| omni-man | 3 | live |
| id | trx_id | roll_ptr | owner | balance | state |
|---|---|---|---|---|---|
| 1 | 750 | - | atom eve | 100 | live |
| 2 | 750 | - | invincible | 200 | live |
| 3 | 750 | - | omni-man | 300 | live |
| record | row | old value | old trx_id | old roll_ptr |
|---|---|---|---|---|
| no undo records | ||||
If the animation is too fast or too slow, change the speed for every visualization on this page:
Change the animation speed
The widget draws one page of each structure and leaves out the tree levels above the leaves. Every operation commits at once, so no transaction is left reading an old version. The sections below each have Watch and Step through buttons that load one case into it.
What an index entry points at
Here are the two layouts with their indexes:
- A PostgreSQL index entry holds a physical address: the TID, a page number and a line pointer number, 6 bytes in all. It says where one version of the row is stored.
- An InnoDB secondary index entry holds a logical address: the row’s primary key value. It says which row is meant, and nothing about where that row is.
Almost every difference in this article follows from that.
A physical address is quick to follow. It names a page, and reading that page gives you the tuple. But it goes stale when a new version of the row is written somewhere else, and then every index has to be told.
A logical address never goes stale as long as the primary key does not change. The row can move to another page and every index entry is still right. But following it means searching a second tree, and it is as wide as the primary key is.
Insert
| PostgreSQL | InnoDB | |
|---|---|---|
| Where the row goes | Any page with room, found through the free space map | The leaf page where its primary key belongs |
| Index entries written | One in every index, the primary key index included | One in every secondary index. The primary key entry is the row |
| What a full page does | The row goes to another page | The page splits, and about half its rows move |
| Rollback | The transaction is recorded as aborted. The tuple waits for VACUUM | The undo record is used to remove the row again |
Insert id 5 and then id 4 in the widget. PostgreSQL appends both to the heap in arrival order, so 4 sits after 5. InnoDB places 4 between 3 and 5. That is why a SELECT * with no ORDER BY returned rows in arrival order in the PostgreSQL article and in key order in the MySQL article.
It also means the order of the keys matters to one design much more than to the other. Random primary keys, such as random UUIDs, hit a random leaf page of the clustered index on every insert, and those pages hold whole rows. In the measurement from the last article, the same 200,000 rows took 520 leaf pages when inserted in key order and 723 when inserted in random order.
PostgreSQL is not immune to this, but it is less exposed. Its heap does not care about key order at all. Its primary key index is still a B+ tree and still splits under random keys, but the entries that move in a split are a key and a 6-byte TID, not a row. Keys that arrive in order in the B+ tree article shows why sorted keys are the easy case for any B+ tree.
Update
This is where the two designs differ most. What matters is which column changed.
| The update changes | PostgreSQL | InnoDB |
|---|---|---|
| A column that no index contains | A new tuple. If it fits on the same page, the update is HOT and no index is touched. If not, every index gets a new entry | The row is changed in place. No index is touched |
| A column in one index | A new tuple, and a new entry in every index | The row is changed in place. That one index gets the old entry delete-marked and a new entry added |
| The primary key | The same as any other indexed column | The row moves: the old row is delete-marked, a new row is inserted, and the entry in every secondary index is replaced |
Run the second case and compare the lines under each engine. PostgreSQL adds an entry to accounts_pkey even though id did not change, because the new version of the row has a new TID and the old entry points at the old one. InnoDB leaves the primary key alone, because the row is still at primary key 2.
Two things follow.
Index count multiplies PostgreSQL’s update cost, and mostly does not touch InnoDB’s. On a table with five indexes, an update to one indexed column writes five index entries in PostgreSQL and changes one index in InnoDB. PostgreSQL’s way out is the HOT update, which is why fillfactor and the choice of which columns to index matter so much there.
The primary key is cheap to change in PostgreSQL and expensive in InnoDB. In PostgreSQL the primary key index is one index among many. In InnoDB the primary key is the row’s position.
The two also keep the old version differently. PostgreSQL leaves the old tuple where it was and writes the whole row again, every column of it. InnoDB copies only the old values of the changed columns to the undo log and overwrites the row. Old versions and cleanup comes back to what that costs later.
Delete
| PostgreSQL | InnoDB | |
|---|---|---|
| The row | xmax is set on the tuple. It stays in the page |
The delete mark is set on the row. It stays in the page |
| The indexes | Not touched | The row’s entry in every secondary index is delete-marked |
| Space freed | None until VACUUM | None until purge |
Both only mark the row, for the same reason: a transaction that started earlier may still need to read it. The difference is in the indexes. A PostgreSQL delete is one small write to the heap, whatever the number of indexes. An InnoDB delete also marks one entry per secondary index.
Reading by primary key
| PostgreSQL | InnoDB | |
|---|---|---|
| One row | Search accounts_pkey, then read one heap page |
Search the clustered index. The row is in the leaf |
| A range of keys | Walk the index leaves, and read a heap page for each entry | Walk the clustered index leaves. The rows are in them |
| What decides the cost of a range | How closely heap order follows key order: the correlation | Nothing else. Neighbouring keys are neighbouring rows |
For one row, the difference is one page read. PostgreSQL’s primary key index is the smaller tree, because its leaves hold a key and a TID where InnoDB’s hold whole rows, but it always needs the extra trip to the heap. In the case above the trip is longer than usual: the row has been updated twice, the index holds two entries for id 2, and the heap has to be asked about each.
For a range, the difference can be large. A query such as WHERE id BETWEEN 1000 AND 2000 is the B+ tree range scan in both databases. In InnoDB the rows come with it, many to a page. In PostgreSQL each of the thousand entries points into the heap, and whether those thousand tuples share a few pages or sit on a thousand different ones depends on how the table was written and updated. PostgreSQL’s CLUSTER command sorts the heap once and does not keep it sorted.
This is the main thing a clustered index buys. Tables that are mostly read by ranges of their primary key, such as all the orders of one customer under a primary key of (customer_id, order_id), suit it well.
Reading by another index
| PostgreSQL | InnoDB | |
|---|---|---|
| One row | Search the index, then read one heap page | Search the index, then search the clustered index: two descents |
| Size of an index entry | Key plus a 6-byte TID | Key plus the whole primary key |
| Reading from the index alone | Index-only scan, for heap pages the visibility map marks all-visible | Covering index, for index pages with no recent changes |
| Many matching rows | Bitmap heap scan: sort the TIDs, read each heap page once | Multi-range read: sort the primary keys, visit the clustered index in order |
Here the costs swap. PostgreSQL goes from the index entry straight to a heap page. InnoDB gets a primary key and has to search a second tree. The upper levels of that tree are almost always in memory, so the second search usually costs one more page read, not three or four. But it is paid for every row the index finds.
The primary key also sets the size of every InnoDB secondary index. A PostgreSQL entry carries 6 bytes whatever the primary key looks like. In the measurement from the last article, switching the primary key from INT to a CHAR(36) UUID took the same secondary index from 278 leaf pages to 686.
Both databases can skip the table when the index holds every column a query needs, and both have the same obstacle: index entries carry no transaction IDs, so the index cannot say which versions a reader may see. PostgreSQL answers with the visibility map, one bit per heap page that VACUUM sets. InnoDB keeps, on every secondary index page, the ID of the newest transaction that changed it. In both, recently changed data falls back to the full lookup.
InnoDB gets one thing free here. Its secondary indexes already hold the primary key, so SELECT id FROM accounts WHERE owner = 'invincible' is covered by an index on owner alone. In PostgreSQL the index needs id added to it first, for example with CREATE INDEX ... ON accounts (owner) INCLUDE (id).
Old versions and cleanup
Both databases use MVCC, and both keep old versions of rows for transactions that started earlier. They disagree on where to keep them.
| PostgreSQL | InnoDB | |
|---|---|---|
| Where old versions live | In the heap, among the live tuples | In the undo log, outside the table |
| Reading the newest version | May pass dead tuples, and index entries that lead to them | No extra work. The row in the table is the newest version |
| Reading an older version | No extra work. It is a complete tuple in the heap | Rebuild it by following the roll pointer through undo records |
| Rollback | Cheap: record the transaction as aborted | Costs as much as the changes it undoes |
| Cleanup | VACUUM scans the heap, skipping all-visible pages | Purge follows the undo log to what it has to remove |
| What a long transaction causes | Dead tuples pile up in the heap and in every index | The undo log grows, and so does the history list length |
| Transaction ID wraparound | IDs are 32 bits, so VACUUM must freeze old tuples | IDs are 48 bits. No freezing |
| Shrinking the file | VACUUM FULL, which holds an exclusive lock that blocks reads and writes for the whole rewrite |
OPTIMIZE TABLE, an online rebuild: reads and writes continue, with brief locks at the start and end |
PostgreSQL’s choice keeps writes and rollbacks simple and makes old versions as cheap to read as new ones. The cost lands on the table itself. Every update leaves a dead tuple in the heap, and a normal update leaves a dead entry in every index as well. Until VACUUM gets to them, scans read past them. A table whose rows are updated often needs VACUUM to keep up, and if it falls behind, the table and its indexes bloat.
InnoDB’s choice keeps the table clean. An update leaves nothing behind in the clustered index, and the garbage collects in one place built for it. The cost lands on transactions that need the past. A long-running report walks back through the undo log for every row that changed since it started, and a large rollback has to undo each change one by one.
Neither escapes the long transaction. One session left open holds back VACUUM in PostgreSQL and purge in InnoDB, for every table.
The B+ trees underneath
Both databases build their indexes on a B+ tree, and neither uses the textbook version from the B+ tree article as it stands. That article and the B-tree article promised a closer look. Here is how the two differ from the textbook and from each other:
| Textbook B+ tree | PostgreSQL | InnoDB | |
|---|---|---|---|
| Page size | Not specified | 8 kB | 16 kB |
| What a leaf entry holds | A key | A key and a TID | Clustered index: the whole row. Secondary index: a key and the primary key |
| Links between pages | Each leaf to the next | Every page to both neighbours on its level, plus a “high key”, the upper bound of the page | Every page to both neighbours on its level |
| Equal keys | Not considered | The TID breaks ties. Since PostgreSQL 13, equal keys are stored once with a list of TIDs | The primary key in each entry makes it unique |
| Splitting a full page | In the middle | In the middle. At the right-hand edge, the old page is left 90% full | In the middle. For keys arriving in order, the old page is left about 15/16 full |
| Removing an entry | At once, then borrow or merge below half full | Left in place until VACUUM, or until the page is about to split | Delete-marked until purge |
| Merging pages | Whenever a page drops below half full | Never. A page is removed only once it is completely empty | With a neighbour, once a page drops below MERGE_THRESHOLD, 50% by default |
Three of these rows are worth a sentence each.
PostgreSQL’s extra links are for concurrency. Its index is the modified B+ tree that Lehman and Yao described in 1981. If a page splits while a search is on its way down to it, the search can compare its key with the page’s high key, see that the key now belongs further right, and follow the link to the new page. Readers do not have to lock the path they came down.
Both special-case sorted inserts. The textbook split leaves two half-full pages. With keys that only ever increase, the left half would never be filled again, so both databases leave the old page nearly full and start a nearly empty one.
Neither rebalances the way the textbook does. In the B-tree widget, every delete borrows or merges straight away. Real indexes delete lazily, because the entry may still be needed by an older transaction and because a page that empties is often filled again soon. PostgreSQL goes furthest: it never merges two partly full pages.
Side by side
| Operation | PostgreSQL heap | InnoDB clustered index |
|---|---|---|
| Insert | Row on any page with room. One entry in every index | Row at its place in key order. One entry in every secondary index |
| Update, column not indexed | New tuple. No index writes if it fits on the same page | In place. No index writes |
| Update, indexed column | New tuple. New entry in every index | In place. One index changes |
| Update, primary key | Like any indexed column | Row moves. Every secondary index changes |
| Delete | Mark the tuple | Mark the row and its secondary index entries |
| Read by primary key | Index, then heap | Index only. The row is in it |
| Range by primary key | Index, then one heap visit per row | Rows read in order from the leaves |
| Read by another index | Index, then heap | Index, then the clustered index |
| Old versions | In the heap. Cleaned by VACUUM | In the undo log. Cleaned by purge |
| Rollback | Cheap | Costs as much as the changes |
| Primary key choice | A constraint like any other | Decides insert position and the size of every index |
What each design is good at
Neither layout is faster in general. Each is cheaper for some workloads, and the tables above say which.
A heap tends to suit:
- Tables read through many different indexes. Every index reaches the row in one hop.
- Long or random primary keys. The key appears once, in its own index, and the heap ignores its order.
- Updates that leave indexed columns alone, on pages with room to spare, where most of them can be HOT.
- Workloads that roll back or delete a lot. Both are a single mark.
Its costs are updates to indexed columns on tables with many indexes, primary key range scans over a heap that has drifted out of order, and VACUUM, which has to keep up.
A clustered index tends to suit:
- Tables read mostly by primary key, and above all by ranges of it.
- Rows that are updated often, on tables with several secondary indexes, where few updates change an indexed column.
- Tables that must not fill up with old versions. The undo log takes them.
Its costs are a second tree search on every secondary index lookup, a primary key that has to be chosen for the storage engine’s sake, and long transactions and large rollbacks, which pay for the tidy table through the undo log.
The numbers in this series come from small tables on one machine. They show the direction of each effect, not its size on your data. Before changing a schema over any of this, measure the workload you have.
What this comparison left out
Four things matter to both designs and did not fit:
- Logging. Both databases write every change to a log before it reaches the data pages, so they can recover after a crash. PostgreSQL calls it the write-ahead log, and InnoDB calls it the redo log.
- Caching. Which pages are in memory decides what a “page read” really costs. PostgreSQL uses its shared buffers and the operating system’s file cache, and InnoDB uses its buffer pool.
- Locking. What happens when two transactions want to change the same row, or the same gap between rows.
- Big values. PostgreSQL’s TOAST tables and InnoDB’s overflow pages.
Those are topics for later articles in this series.