SteelReed

Search

Search posts, questions…

4. Database & SQL

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.

18 Nov 20268 min readSenior

–

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.

SQL
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 / 50

UNIQUE 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 on a leaves b only to locate the starting point. a >= 97 AND b = 2 shows key_len = 8 on MySQL but still scans ~63,000 entries; a IN (97, 98, 99) AND b = 2 scans 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 CONCURRENTLY brings 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 with pg_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 bigint or 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) or LOCK=NONE (MySQL), outside a transaction.
  • The migration checks pg_index.indisvalid after CONCURRENTLY; on failure, DROP INDEX CONCURRENTLY and 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 bigint as 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_at anyway). Store it as uuid, not text.

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 ALTER need an exclusive metadata lock. The 13:20 session holds a shared one (open transaction), the ALTER queues behind it, and every new query, SELECT included, queues behind the ALTER.
  • 15 minutes: KILL the ALTER session (or the 13:20 session once you've confirmed it's harmless); queries resume immediately.
  • Root fix: before ALTER, check information_schema.innodb_trx for long transactions; SET SESSION lock_wait_timeout = 5 so the ALTER gives up instead of freezing the table; find where the app forgets to commit. PostgreSQL is similar with lock_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: bigint or 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

All SQL & Query Tuning questions →All Data Modeling & Scaling questions →

Loading comments…
Next on the roadmapHow SQL runs and how to read a PostgreSQL execution plan