Inside an index: B-trees, B+trees, clustered tables, heaps and choosing a primary key
Why databases use B+trees, how an InnoDB clustered index differs from a PostgreSQL heap, how unique indexes treat NULL, composite indexes with range predicates, bigint vs UUIDv4 vs UUIDv7 as a primary key, and maintaining indexes once they bloat.
On this page
1. The problem
A 1-million-row orders table uses UUIDv4 as its primary key: the PK index is 38 MB instead of 21 MB with bigint, and every 200,000 inserts write 60 MB of WAL instead of 27 MB. No errors, just slower and costlier.
2. Key idea
Foreign keys: InnoDB indexes the child column automatically, PostgreSQL does not.
A B+tree node is a page (16 KB in InnoDB, 8 KB in PostgreSQL). Inner nodes hold only separator keys, so fan-out is large; the upper levels stay in RAM and a lookup usually costs one disk read. A range scan walks sideways along the leaves.
| InnoDB | PostgreSQL | |
|---|---|---|
| The table is | a B+tree ordered by PK (clustered index) | a heap, rows in insertion order |
| Secondary leaves hold | column values + PK | a TID (page + slot) |
| Reading via a secondary | two tree walks | one tree walk, then a jump into the heap |
| The cost | a big PK bloats every secondary | a non-HOT update adds entries to every index |
HOT update: if no indexed column changes and the page has room, no index is touched. For update-heavy tables, lower fillfactor to 80–90. InnoDB doesn't let you choose any clustering column: to change it, change the PK.
2.1 How do you pick a primary key?
Increasing keys insert at the rightmost leaf, so pages stay full; random keys insert mid-tree, so pages split in half (page split), each half ~50% full.
| Key type | Use when | Don't use when |
|---|---|---|
bigint identity |
the default, one DB generates ids | ids appear on public URLs, clients must generate them first |
| UUIDv7 / ULID | distributed or offline generation, public ids | you don't want to reveal creation time |
| Snowflake | a distributed bigint |
you can't manage machine ids and clocks |
A common setup: a bigint PK plus a unique UUIDv7 column as the public id.
3. In SQL
PostgreSQL: a compact PK, a separate public id, leaf density measured.
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
public_id uuid NOT NULL UNIQUE DEFAULT uuidv7(), -- PostgreSQL 18; older versions generate in the app
user_id bigint NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
) WITH (fillfactor = 90); -- leave room for HOT updates
CREATE INDEX CONCURRENTLY orders_user_created ON orders (user_id, created_at);
CREATE EXTENSION IF NOT EXISTS pgstattuple;
SELECT avg_leaf_density, leaf_fragmentation FROM pgstatindex('orders_pkey');
-- bigint: ~90 / 0 UUIDv4: ~71 / 50UNIQUE allows many NULLs; to forbid that use NULLS NOT DISTINCT (PostgreSQL 15+) or a partial unique index.
Composite indexes with ranges, bloat, and when not to index
- Index
(a, b): a range onaleavesbonly to locate the starting point.a >= 97 AND b = 2showskey_len = 8on MySQL but still scans ~63,000 entries;a IN (97, 98, 99) AND b = 2scans just 30. - Without the leading column an index can still be used via skip scan (MySQL 8.0.13+, PostgreSQL 18) when the leading column has few values. Putting the high-cardinality column first "for more branches" is wrong: tree height doesn't depend on column order.
- Delete 90% of rows then
VACUUM: the PK index stays 21 MB with 9% leaf density;REINDEX INDEX CONCURRENTLYbrings it to 2.2 MB. Rebuild when density stays low, not on a schedule. - Don't index: small tables, low-cardinality evenly distributed columns, write-mostly tables like raw logs, columns never used in
WHERE,JOIN,ORDER BY. Find unused indexes withpg_stat_user_indexes(idx_scan = 0).
4. Working with AI
Hand to AI: index migrations, pgstatindex measurement scripts.
Check in AI-written code:
- The PK is
bigintor UUIDv7, not UUIDv4, for large tables. - PostgreSQL foreign keys have a child-column index if you join on them or delete parents.
- Indexes on live tables use
CONCURRENTLY(PostgreSQL) orLOCK=NONE(MySQL), outside a transaction. - The migration checks
pg_index.indisvalidafterCONCURRENTLY; on failure,DROP INDEX CONCURRENTLYand retry. - A nullable UNIQUE column is intentional, not assumed to block duplicates.
5. Exercises
Exercise 1: Pick a primary key for orders
PostgreSQL, 5 million orders a month; the mobile app creates orders offline and syncs later (ids generated on the client); ids appear on public URLs. The AI suggests UUIDv4 "to be standard". Choose and explain.
Solution to Exercise 1
- Rule out
bigintas the only id: clients can't generate it ahead of time, and it reveals order volume. - Rule out UUIDv4: the table will reach hundreds of millions of rows; the index is ~80% bigger and WAL doubles from page splits.
- Pick UUIDv7 as the PK: clients can generate it, it's nearly increasing so the index stays compact (~90% leaf density), and the next id can't be guessed. Accept revealing creation time (orders have
created_atanyway). Store it asuuid, nottext.
Exercise 2: Read a metadata-lock incident
MySQL 8.4. At 14:00 you run ALTER TABLE orders ADD INDEX idx_status (status), ALGORITHM=INPLACE, LOCK=NONE. At 14:01 every SELECT on orders hangs and the connection pool runs dry; SHOW PROCESSLIST is full of Waiting for table metadata lock. A session from 13:20 sits in Sleep with an uncommitted transaction. Diagnose it, say what you do in the first 15 minutes, and fix the root cause.
Solution to Exercise 2
- Diagnosis: the start and end of
ALTERneed an exclusive metadata lock. The 13:20 session holds a shared one (open transaction), theALTERqueues behind it, and every new query,SELECTincluded, queues behind theALTER. - 15 minutes:
KILLtheALTERsession (or the 13:20 session once you've confirmed it's harmless); queries resume immediately. - Root fix: before
ALTER, checkinformation_schema.innodb_trxfor long transactions;SET SESSION lock_wait_timeout = 5so theALTERgives up instead of freezing the table; find where the app forgets to commit. PostgreSQL is similar withlock_timeout.
Summary
- B+tree: data in leaves, linked leaves, 3 levels for tens of millions of rows.
- InnoDB reads via a secondary in two tree walks; a big PK bloats every index.
- PostgreSQL: non-HOT updates add entries to every index; lower
fillfactor. - PK:
bigintor UUIDv7, avoid UUIDv4. - Measure bloat before rebuilding; online index builds can leave INVALID indexes or hit metadata locks.
Read more: PostgreSQL index lab on an airline dataset.
Practice interview questions on this topic
- How does a primary key differ from a unique key, and a key from an index?
- What is a clustered index, and how do InnoDB and PostgreSQL storage models affect index design?
- How do you index a table: what do you base it on, which columns, and how many is enough?
- What is an index, why does it speed up queries, and why do databases use B+trees?
- How do you decide on and add an index (even unique) to a 200-million-row production table?
- Which queries can a composite index (a, b, c) serve, and how should you order its columns?
All SQL & Query Tuning questions →All Data Modeling & Scaling questions →
Comments
Community rules