B-Tree vs B+Tree in Production Databases
"The B-tree is, de facto, the standard organization for indexes in a database system." — Douglas Comer, The Ubiquitous B-Tree, ACM Computing Surveys 11(2), June 1979
Summary: why databases index with page-sized, high-fan-out trees, how the original B-tree differs from the B+tree every major engine actually ships, and what page splits, fill factor and key choice do to the index you run in production. Focus: fan-out and height arithmetic, node = page, leaf links and range scans, page splits and merges, right-most vs random inserts, Lehman–Yao concurrency, PostgreSQL deduplication / bottom-up deletion / suffix truncation, PostgreSQL heap + TID vs InnoDB clustered index + PK. Learning goal: you can estimate the height and size of any index on paper, predict how a key type (bigint identity, UUIDv4, UUIDv7) will split pages, read pgstatindex and bt_page_items output, and decide when to REINDEX.
This page is the complete reference for the tree that sits behind almost every relational index: the original B-tree of Bayer and McCreight, the B+tree described by Comer, the B-link tree of Lehman and Yao, and what PostgreSQL (nbtree), MySQL InnoDB, SQL Server, SQLite and MongoDB WiredTiger really build. It covers the arithmetic (pages, fan-out, height, I/O), the life of a page (split, merge, fill factor, deduplication, bloat) and the storage cost of the two table layouts (heap + index vs clustered index). Neighbouring pages own the rest: index types and index design (multicolumn, partial, GIN, GiST, hash) are in Indexing; LSM-trees, compaction and write amplification across engines are in Storage Engines; heap pages, tuples and ctid are in Database Internals; dead tuples, VACUUM and HOT are in MVCC, VACUUM & Bloat; which ID to generate is in ID Generation and Schema Design; reading plans is in Query Planning.
Page map
| If you are looking for | Go to |
|---|---|
| The tables to memorise | Everything in one minute |
| Why a tree at all: full table scan arithmetic, binary search tree limits | Why B-trees exist |
| Bayer & McCreight, Comer, Lehman & Yao, Prefix B-trees | Where it comes from |
| B-tree vs B+tree, fan-out, page splits, fill factor, right-most inserts, dedup, suffix truncation | The concepts, one by one |
| The two pictures: node layout and page split | B-tree vs B+tree, Page split |
| PostgreSQL vs InnoDB vs SQL Server vs SQLite vs MongoDB | Per-engine behaviour |
| Page layout, B-link trees, latch coupling, knobs | Mechanics |
| UUID keys, bloated indexes, wide InnoDB PKs, range queries | Solving the classic problems |
| A B+tree in Go, migrations and an index-health command in Laravel | Go, Laravel |
| Which key, which fill factor, which index | Choosing |
| Monolith to distributed: where B-trees matter | In architecture |
pgstatindex, pageinspect, EXPLAIN experiments | Lab |
| Wrong beliefs, cheat sheet, questions, every term | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The structures.
| Structure | Where keys live | Leaves linked? | Who uses it |
|---|---|---|---|
| Binary search tree | One key per node, two children | No | In-memory maps; never on disk (too tall) |
| B-tree (Bayer & McCreight 1970/1972) | Every node holds keys and their data/row pointers | No | SQLite index b-trees; textbooks |
| B+tree (Knuth's variant, named by Comer 1979) | Internal nodes hold separators only; every entry is in a leaf | Yes (sequence set) | PostgreSQL, InnoDB, SQL Server, Oracle, WiredTiger |
| B-link tree (Lehman & Yao 1981) | As B+tree, plus a high key and right-link on every level | Yes, every level | PostgreSQL nbtree |
| B*-tree (Knuth) | B-tree that redistributes to siblings before splitting, nodes at least 2/3 full | Varies | The name is often (wrongly) used for B+tree |
The numbers worth knowing (PostgreSQL 8 kB pages; computed on this page, see index size estimation).
| Quantity | Value | Why |
|---|---|---|
Entries per leaf, bigint key | ~407 max, ~366 at fillfactor 90 | 16-byte index tuple + 4-byte line pointer in ~8,150 usable bytes |
Entries per leaf, uuid key | ~291 max, ~262 at fillfactor 90 | 24-byte index tuple + 4-byte line pointer |
Height for 1 million bigint keys | 3 levels | 2,725 leaves → 7 internal → root |
Height for 1 billion bigint keys | 4 levels | 2.7 M leaves → 6,695 → 17 → root |
Height for 10 billion bigint keys | still 4 levels | the root just has more children |
| Point lookup | height page reads + 1 heap read | top levels almost always cached |
| Full table scan of 100 M rows (~150 B each) | ~1.8 M pages, ~15 GB | 7–75 s at 2,000–200 MB/s sequential |
| Binary search tree over 1 billion keys | at least 30 levels | log2(10^9) ≈ 30 random reads |
The three rules to act on.
| Situation | Do this |
|---|---|
| Choosing a primary key on a write-heavy table | Prefer an ever-increasing key (bigint identity or UUIDv7) so inserts hit the right-most leaf; avoid UUIDv4 as a clustered key in InnoDB |
| Index much larger than expected | pgstatindex: if avg_leaf_density is far below the fillfactor, run REINDEX INDEX CONCURRENTLY (PostgreSQL) or OPTIMIZE TABLE / ALTER TABLE ... FORCE (InnoDB) |
| Many secondary indexes in InnoDB | Keep the primary key short: every secondary entry repeats it |
Why B-trees exist
A disk (or SSD, or the OS page cache) does not hand out bytes; it hands out pages. PostgreSQL reads 8 kB pages, InnoDB 16 kB pages by default, SQLite 4 kB. The cost of a query is therefore roughly how many pages it must touch, and whether those pages are next to each other (sequential I/O) or scattered (random I/O). An index exists to turn “touch every page of the table” into “touch a handful of pages”.
Full table scan arithmetic Must-know
In plain words: without an index the database reads the whole table to find one row. The cost grows with table size, not with the size of the answer.
Common misunderstanding: “A full table scan is always the slow path.” For a query that returns a large fraction of the table, a sequential scan is the fast path: reading pages in order is several times cheaper per page than jumping around, which is exactly why PostgreSQL's default random_page_cost = 4 is four times seq_page_cost = 1.
Definition: a full table scan (PostgreSQL Seq Scan, MySQL type: ALL) reads every page of the table, in file order, and tests each row. Cost ≈ number of pages × sequential page cost + number of rows × per-row CPU cost.
Table orders: 100,000,000 rows, ~120 bytes of data per row
1 row size on a heap page = 24 (tuple header) + 120 (data) + 4 (line pointer) ≈ 148 bytes
2 rows per 8 kB page = (8192 - 24 page header) / 148 ≈ 55
3 pages = 100,000,000 / 55 ≈ 1,818,182 pages ≈ 14.9 GB
4 sequential read = 14.9 GB / 500 MB/s ≈ 30 s (7 s at 2 GB/s NVMe, 74 s at 200 MB/s)
5 same row via a B+tree = 4 index pages + 1 heap page = 5 page reads ≈ 0.5 ms cold on SSD,
usually 1-2 real reads because the root and internal pages stay cachedReal scenarios: an admin search by email on a 50 M-row users table with no index (seconds per request, a pool of connections pinned); a nightly report that should seq-scan because it aggregates everything; a DELETE ... WHERE created_at < now() - interval '90 days' that seq-scans because created_at has no index.
| Engine | Name in the plan | Knob that prices it |
|---|---|---|
| PostgreSQL | Seq Scan (and Parallel Seq Scan) | seq_page_cost, random_page_cost, effective_cache_size |
| MySQL InnoDB | type: ALL in EXPLAIN (a scan of the clustered index) | optimizer cost model tables mysql.server_cost / mysql.engine_cost |
| SQL Server | Table Scan (heap) / Clustered Index Scan | none exposed per query |
| SQLite | SCAN orders in EXPLAIN QUERY PLAN | none |
Fix: an index on the predicate column; and for reports that must read everything, let the scan happen but keep it off the primary (replica, columnar store; see OLTP vs OLAP).
Why not a binary search tree? Important
In plain words: a binary search tree halves the search space at each node, which is perfect in memory but terrible on disk: each halving is a separate random page read.
Common misunderstanding: “O(log n) is O(log n).” The base matters. log2 of one billion is about 30; log base 400 of one billion is about 3.5. Thirty random reads versus four is the difference between 3 ms and 0.4 ms on an SSD, and between 300 ms and 40 ms on a spinning disk.
Definition: a binary search tree (BST) stores one key per node with at most two children; balanced variants (AVL, red-black) guarantee height about log2(n). A plain BST built from sorted input degenerates into a linked list of height n.
Insert 1, 2, 3, 4, 5 into a plain BST Same keys, B+tree with 4 keys per page
1 1 1 [1 2 3 4]
2 \ 2 insert 5 -> split
3 2 3 [4]
4 \ 4 / \
5 3 ... height 5 = 5 random reads 5 [1 2 3] [4 5] height 2, always balancedReal scenarios: an in-memory red-black tree (Java TreeMap, C++ std::map) is fine because every node is already in RAM; the same structure on disk would need one I/O per level. Bayer and McCreight's 1970 abstract is about exactly this: an index "kept on some pseudo random access backup store like a disc or a drum", where each access has "a rather long access or wait time".
| Tree | Keys per node | Height for 10^9 keys | Page reads per lookup |
|---|---|---|---|
| Balanced BST | 1 | ≥ 30 | ≥ 30 |
B+tree, bigint, 8 kB page | ~366–407 | 4 | 4 (1–2 when cached) |
B+tree, uuid, 8 kB page | ~262–291 | 4 | 4 |
InnoDB B+tree, bigint PK, 16 kB page | ~1,000 in internal pages | 3–4 | 3–4 |
Fix: make each node a whole page, so one I/O brings hundreds of keys: that is the B-tree.
The trade-off, and the analogy we reuse
| Wide, shallow tree (B+tree) | Narrow, deep tree (BST) |
|---|---|
| Hundreds of keys per node, height 3–4 | Two children per node, height ~30 |
| One page read per level | One page read per level, many more levels |
| Inserts sometimes split a page (extra write) | Inserts rotate nodes (cheap in RAM, many random writes on disk) |
| Leaves in key order: range scans read neighbours | In-order traversal jumps all over memory |
| Space slack (pages 50–100% full) | Pointer overhead per key |
The analogy: a printed telephone directory with a thumb index. The thumb tabs (A, B, C...) are the root; the bold words at the top of each page (“Mansfield – Martin”) are the internal separators; the pages themselves are the leaves, in order, so “everyone named Martin” is a few consecutive pages. A classic B-tree would print some full entries on the thumb tabs themselves; a B+tree prints only guide words there and keeps every real entry on the pages. When a new name does not fit on a page, the publisher inserts a new page and adds a guide word: a page split. We come back to this directory throughout.
Three common misunderstandings, up front
- “PostgreSQL and MySQL use B-trees, not B+trees.” Both manuals say B-tree. Structurally both are B+trees: internal pages hold only navigation keys, every entry that points to a row is in a leaf, and leaves are linked. SQL Server's manual uses the precise term: "Rowstore indexes are organized as B+ trees."
- “A bigger table means a much deeper index.” Height grows with the logarithm in base fan-out. Going from one million to ten billion
bigintkeys adds one level. - “Random UUID keys only cost 8 extra bytes.” They also put every insert on a random leaf, which splits pages 50/50, leaves them about 69% full on average, dirties random pages all over the buffer pool and, in InnoDB, scatters the table itself.
Where it comes from
1970–1972, Bayer and McCreight. Rudolf Bayer and Edward McCreight, at Boeing Scientific Research Laboratories, published Organization and Maintenance of Large Ordered Indices as a July 1970 report and in Acta Informatica 1 (1972). The quotes on this page come from the 1970 report, which is the version that is freely readable. Its key idea is the page as the node: "The pages themselves are the nodes of a rather specialized tree, a so-called B-tree". Their Definition 2.1 fixes the shape for a parameter k: "Each path from the root to any leaf has the same length h", "Each node except the root and the leaves has at least k + 1 sons", and "Each node has at most 2k + 1 sons". The abstract states the space guarantee practitioners still quote: "Storage utilization is at least 50% but generally much higher." The paper never explains the letter B; Comer: "The origin of" the name "has never been explained by" the authors.
1973, Knuth. The Art of Computer Programming, volume 3, describes the variant that keeps all records in the leaves, and the B*-tree that redistributes keys to keep nodes two-thirds full. SQLite's file format still cites "Knuth, The Art Of Computer Programming, Volume 3" as its background reading.
1977, Bayer and Unterauer. Prefix B-Trees shows that internal separators do not need to be real keys, only something that separates the two sides, so they can be shortened. This is the ancestor of PostgreSQL's suffix truncation; the nbtree README says "The technique was first described by Bayer and Unterauer".
1979, Comer. The Ubiquitous B-Tree surveys the variants and gives the B+tree its name: "In a B+-tree, all keys reside in the leaves." The upper levels "consist only of an index, a roadmap"; leaf nodes are linked left to right, and "The linked list of leaves is referred to as the sequence set." He uses "B+-tree for Knuth's unnamed implementation" to avoid confusion with the B*-tree.
1981, Lehman and Yao. Efficient Locking for Concurrent Operations on B-Trees (ACM TODS 6(4)) adds one pointer per node: "A single additional" link pointer "in each node allows a process to easily recover from tree modifications performed by other concurrent processes". PostgreSQL's nbtree README opens with: "This directory contains a correct implementation of Lehman and Yao's high-concurrency B-tree management algorithm".
2010–2011, Graefe. Goetz Graefe's A Survey of B-Tree Locking Techniques (ACM TODS 35(3), 2010) separates latches (short-term, protect in-memory pages) from locks (transactional, protect keys) and notes that the traditional "lock coupling" is better called "latch coupling". His monograph Modern B-Tree Techniques (Foundations and Trends in Databases, 2011) catalogues the rest; it is not freely available and was not read for this page.
The concepts, one by one
Each block: plain words, the usual wrong belief, a precise definition, a step-by-step sequence, real scenarios, what each engine does, and the fix in SQL (Go and Laravel code is in Go and Laravel).
B-tree vs B+tree Must-know
In plain words: a classic B-tree stores each key (with its row pointer) exactly once, in whatever node it lands, including the root. A B+tree keeps only signposts in the upper levels and puts every key in the bottom level, where the pages are chained together in order.
Common misunderstanding: “A B-tree is better because some lookups stop early at the root.” Very few do: with hundreds of keys per page, over 99% of entries are in leaves anyway (PostgreSQL: "Typically, over 99% of all pages are leaf pages."). Meanwhile putting row pointers in internal nodes makes them fatter, which lowers fan-out and adds height for everyone.
Definition:
| Property | B-tree (Bayer & McCreight) | B+tree (Comer's naming) |
|---|---|---|
| Order | Every node except the root has k to 2k keys (k+1 to 2k+1 children) | Same bounds; leaf and internal capacities may differ |
| Where entries live | Any node: keys in all nodes | Leaves only: keys only in leaves |
| Internal node content | Keys + row pointers + child pointers | Separators (copies or shortened keys) + child pointers |
| Duplicate key in index | Never | A separator may equal a leaf key (it was copied up) |
| Leaf links | None | Left-to-right (sequence set); PostgreSQL links both directions |
| Lookup cost | 1 to h pages | Always h pages |
| Range scan | In-order traversal up and down the tree | One descent, then walk the leaf chain |
| Delete | May need to pull a key up from a leaf to fill an internal node | Remove from the leaf; separators can stay (Comer's Figure 14) |
The word order is used inconsistently: Bayer and McCreight's k is the minimum number of keys per non-root node; Knuth's order m is the maximum number of children. In real engines neither is fixed: capacity is “as many entries as fit in the page”, so variable-length keys give variable fan-out.
Lookup of key 40 (classic B-tree, root = [40 70]) Lookup of key 40 (B+tree, root = [40 70])
1 read root: 40 found, row pointer is here: done 1 read root: 40 is a separator: go right of 40
2 read leaf [40 50 60]: 40 found, row pointer
Lookup of key 50 Lookup of key 50
1 read root 1 read root
2 read leaf [50 60]: found 2 read leaf [40 50 60]: foundReal scenarios: every relational index you create; SQLite's index b-trees are the rare classic B-tree in production (interior cells hold real index entries), while its table b-trees are B+tree-like ("Interior table b-trees hold only keys and pointers to children").
| Engine | Structure behind a plain index |
|---|---|
PostgreSQL nbtree | B+tree with Lehman–Yao high keys and right-links on every level, plus left-links |
| MySQL InnoDB | B+tree; leaves of each level are doubly linked; the clustered index leaf holds the row |
| SQL Server | B+tree ("Rowstore indexes are organized as B+ trees"); leaf level doubly linked |
| Oracle | B+tree-style index; leaf blocks doubly linked |
| SQLite | Index b-trees: classic B-tree; table b-trees (rowid): data only in leaves; no sibling pointers in the format |
| MongoDB WiredTiger | B+tree-style pages for collections and indexes, with index prefix compression |
Fix / how to use it: nothing to choose: you get a B+tree when you write CREATE INDEX. What you choose is the key (width and order) and the fill factor, which the rest of this page is about.
Fan-out and height Must-know
In plain words: fan-out is how many children one page can point to. Height is how many pages you read from root to leaf. Big fan-out means small height.
Common misunderstanding: “Height depends mainly on the number of rows.” It depends far more on the key width: a 100-byte text key cuts fan-out by a factor of five compared with a bigint, and can add a level that a billion extra rows would not.
Definition: with fan-out f and N entries in leaves of capacity L, the number of leaves is N/L and height h = 1 + ceil(log_f(N/L)). With f ≈ 400 each extra level multiplies capacity by 400: 3 levels hold ~60 M bigint entries, 4 levels ~24 billion.
bigint index, PostgreSQL, fillfactor 90 (366 entries per leaf, ~407 per internal page)
1 N = 1,000,000 leaves = 2,725 -> internal 7 -> root : 3 levels
2 N = 100,000,000 leaves = 272,480 -> 670 -> 2 -> root : 4 levels
3 N = 1,000,000,000 leaves = 2,724,796 -> 6,695 -> 17 -> root : 4 levels
4 N = 10,000,000,000 leaves = 27,247,957 -> 66,949 -> 165 -> root : 4 levels
5 uuid instead of bigint at N = 1e9: 3.8 M leaves, still 4 levels, but 31 GB of leaves instead of 22 GBReal scenarios: a 2-billion-row event table whose primary key index is 4 levels deep; a composite index (tenant_id, email) with long emails that is one level deeper than the bigint index on the same table; an index on a 200-byte URL column that is both deep and huge (a hash index, or an index on md5(url), is the usual fix; see Indexing).
| Engine | Page size | Typical fan-out for an 8-byte key |
|---|---|---|
| PostgreSQL | 8 kB (compile-time BLCKSZ) | ~400 |
| MySQL InnoDB | 16 kB default (innodb_page_size 4k–64k, fixed at initialisation) | ~1,000 in internal pages |
| SQL Server | 8 kB | ~500–600 |
| SQLite | 4 kB default (PRAGMA page_size, 512–65536) | ~300–400 |
Fix: keep index keys narrow (bigint over uuid over text), let suffix truncation work (PostgreSQL 12+), use INCLUDE columns for covering instead of extra key columns (they are truncated out of internal pages), and measure height with bt_metap() or pgstatindex().tree_level.
Node = page, point lookups, sequential vs random I/O Must-know
In plain words: each tree node is one database page. A point lookup reads one page per level; a range scan reads pages that are logically next to each other.
Common misunderstanding: “An index lookup costs h disk reads.” In a warm database the root and the internal levels are tiny (the internal levels of a 1-billion-row bigint index are ~6,700 pages, about 55 MB) and live in shared_buffers / the InnoDB buffer pool. Real I/O is usually the leaf plus the table page.
Definition: a point lookup is WHERE key = constant resolved by descending root → internal → leaf; cost is h page accesses (logical reads) plus, in PostgreSQL, one heap access per matching row unless an index-only scan can use the visibility map. Sequential I/O reads adjacent pages (read-ahead helps, one seek per run); random I/O reads unrelated pages (one seek or SSD command per page).
SELECT * FROM orders WHERE id = 734221; -- PostgreSQL, 4-level index, warm cache
1 root page -> shared_buffers hit
2 internal level 1 -> shared_buffers hit
3 internal level 2 -> shared_buffers hit
4 leaf page -> maybe a read (8 kB)
5 heap page (TID) -> maybe a read (8 kB)
EXPLAIN (ANALYZE, BUFFERS): Buffers: shared hit=3 read=2Real scenarios: an API's GET /orders/:id is 1–2 physical reads at most; a WHERE customer_id = ? returning 500 orders scattered across the heap is 500 random heap reads (the reason PostgreSQL switches to a bitmap heap scan, and the reason InnoDB clustering by (customer_id, id) can help).
| Engine | Cache that keeps upper levels hot | How to see page reads |
|---|---|---|
| PostgreSQL | shared_buffers + OS page cache | EXPLAIN (ANALYZE, BUFFERS), pg_statio_user_indexes |
| MySQL InnoDB | buffer pool (innodb_buffer_pool_size) | Innodb_buffer_pool_reads vs _read_requests, EXPLAIN ANALYZE |
| SQL Server | buffer pool | SET STATISTICS IO ON (logical/physical reads) |
| SQLite | page cache (PRAGMA cache_size) | none built in |
Fix: size the cache so at least all internal pages of your hot indexes fit; use covering indexes (INCLUDE) to drop the heap read; keep random_page_cost realistic for SSDs (1.1–2 is common) so the planner does not over-prefer seq scans.
Page split Must-know
In plain words: when a new entry does not fit in its leaf, the database allocates a new page, moves part of the entries there, and adds a pointer to the new page in the parent. If the parent is full, it splits too. When the root splits, the tree grows one level.
Common misunderstanding: “Splits are rare and free.” On a random-key index under load they happen constantly, each one writes at least three pages (old, new, parent) to the WAL/redo log, often as full-page images after a checkpoint, and leaves two half-empty pages behind.
Definition: PostgreSQL: "A page split operation makes room for items that originally belonged on the overflowing page by moving a portion of the items to a new page." The new downlink "may cause the parent to split in turn"; "When the root page finally cannot fit a new downlink, a root page split operation takes place." Leaf splits copy the first right key (or a truncated version of it) up as the separator; internal splits move the middle separator up.
Leaf capacity 4. Insert 25 into [10 20 30 40]:
1 find leaf: [10 20 30 40] is full
2 allocate new page R, move upper half: L = [10 20 25], R = [30 40]
3 R.next = L.next; L.next = R -- right-link first (Lehman-Yao order)
4 insert separator 30 + downlink to R into the parent
5 parent full? split it the same way and push its middle separator up
6 root split? new root with two children: height + 1Real scenarios: an orders table keyed by UUIDv4 doing 3,000 inserts/s splits a leaf about every 200 inserts (~15 splits/s), but every insert dirties a random leaf somewhere in the index, so after each checkpoint far more distinct pages need a full-page image in the WAL than with an append key; a sessions table with a random token as InnoDB primary key moves whole rows on every split because the leaf is the row.
| Engine | What a split moves | Where to see it |
|---|---|---|
| PostgreSQL | Index tuples (TIDs), never heap rows | indirectly: pgstatindex leaf counts, WAL volume (pg_stat_wal) |
| InnoDB clustered index | Whole rows (the leaf is the table) | INFORMATION_SCHEMA.INNODB_METRICS index_page_splits (enable the counter) |
| InnoDB secondary | Key + PK entries | same counters |
| SQL Server | Rows (clustered) or index rows; "bad" mid-page splits log a lot | sys.dm_db_index_operational_stats.leaf_allocation_count |
Fix: ever-increasing keys (see right-most inserts), a lower fill factor on indexes that take random inserts, and periodic rebuilds where density has collapsed.
Merge, page deletion and underflow Important
In plain words: the textbook B-tree merges a page with a neighbour when it drops below half full. Real engines are lazier: PostgreSQL removes a page only when it is completely empty, and InnoDB merges when a page falls below a threshold you can configure.
Common misunderstanding: “Deleting half the rows shrinks the index by half.” In PostgreSQL the pages stay allocated (and mostly empty) until VACUUM deletes empty pages and they are recycled; the file does not shrink without REINDEX.
Definition: Bayer & McCreight's trees "grow and contract in only one way, namely nodes split off a brother, or two brothers are merged" (or keys are redistributed between brothers). PostgreSQL follows Lanin & Shasha's simplified deletion: only empty leaf pages are unlinked and later recycled; half-empty pages stay. InnoDB: "If the fill factor of an InnoDB index page drops below the MERGE_THRESHOLD, which is 50% by default if not specified, InnoDB tries to contract the index tree to free the page."
InnoDB, MERGE_THRESHOLD = 50:
1 page P is 52% full; DELETE removes rows -> 48%
2 InnoDB checks left/right neighbour; merged size fits in one page?
3 yes: rows move into the neighbour, P is freed, parent loses a downlink
4 later INSERTs into that key range fill the merged page past 100% -> split again
"If both pages are close to 50% full, a page split can occur soon after the pages are merged."Real scenarios: a queue table (insert at the right, delete at the left) in PostgreSQL leaves a trail of empty left pages that VACUUM recycles; a purge of old tenants leaves PostgreSQL indexes 30% dense; InnoDB tables with insert/delete churn around the same keys thrash between merge and split.
| Engine | Merge rule | Knob |
|---|---|---|
| PostgreSQL | Only empty pages are deleted (by VACUUM), then recycled via the free space map | none; REINDEX to compact |
| InnoDB | Merge when below MERGE_THRESHOLD (default 50, range 1–50) | COMMENT='MERGE_THRESHOLD=45' on table or index |
| SQL Server | No automatic merge; ghost cleanup removes deleted rows | ALTER INDEX ... REORGANIZE compacts leaf pages |
| SQLite | Rebalances siblings on delete (balance()), frees pages to the freelist | VACUUM, PRAGMA auto_vacuum |
Fix:
-- InnoDB: merge earlier/later to avoid merge-split thrash
ALTER TABLE events COMMENT = 'MERGE_THRESHOLD=40';
CREATE INDEX idx_events_user ON events (user_id) COMMENT 'MERGE_THRESHOLD=40';
-- PostgreSQL: compact after a mass delete
REINDEX INDEX CONCURRENTLY orders_customer_id_idx;Fill factor Important
In plain words: fill factor is how full the database packs pages when it builds an index (or appends at the right edge), leaving the rest free for future inserts and updates into that page.
Common misunderstanding: “fillfactor = 100 gives the smallest, fastest index.” Only for a table that never changes. PostgreSQL warns: "A fillfactor setting of 100 otherwise risks harming performance: even a few updates or inserts will cause a sudden flood of page splits."
Definition: PostgreSQL B-tree fillfactor (10–100, default 90): "leaf pages are filled to this percentage during initial index builds, and also when extending the index at the right (adding new largest key values)." InnoDB leaves 1/16 free in clustered-index pages; innodb_fill_factor (default 100, which still leaves 1/16 free) applies only to sorted index builds. SQL Server FILLFACTOR (0 = 100) applies at build/rebuild only.
PostgreSQL index built with fillfactor 70, then random inserts:
1 CREATE INDEX ... WITH (fillfactor = 70) -- each leaf 70% full, 30% slack
2 random inserts land in slack: no split until a page reaches 100%
3 after the slack is used, split rate returns to normal (50/50 splits)
4 the index started ~28% larger than at fillfactor 90 (for the same rows)Real scenarios: an index on updated_at or status that receives many non-HOT updates; a static lookup table (countries, currencies) where fillfactor = 100 is safe; an InnoDB ALTER TABLE ... ENGINE=InnoDB rebuild that packs pages to innodb_fill_factor.
| Engine | Setting | Default | Applies when |
|---|---|---|---|
| PostgreSQL index | WITH (fillfactor = n) | 90 (B-tree) | Build, REINDEX, and right-most appends |
| PostgreSQL table | ALTER TABLE ... SET (fillfactor = n) | 100 | Heap pages; leaves room for HOT updates |
| InnoDB | innodb_fill_factor (global) | 100 (1/16 still kept free) | Sorted index builds only |
| SQL Server | WITH (FILLFACTOR = n), PAD_INDEX | 0 (= 100) | Create/rebuild only |
| SQLite | none | n/a | n/a |
Fix:
CREATE UNIQUE INDEX title_idx ON films (title) WITH (fillfactor = 70); -- example from the PostgreSQL manual
ALTER INDEX orders_status_idx SET (fillfactor = 80);
REINDEX INDEX CONCURRENTLY orders_status_idx; -- a changed fillfactor applies to new pages; rebuild to apply everywhereRange scan along the leaf links Must-know
In plain words: to read “all keys between 30 and 70”, the database descends once to the leaf holding 30, then walks right along the leaf chain until it passes 70. Internal pages are never visited again.
Common misunderstanding: “A range query costs one lookup per row.” It costs one descent plus one page per leaf covered; with ~366 entries per leaf, 10,000 matching keys are ~28 leaf pages. (In PostgreSQL the heap fetches are a separate cost, which is why index-only scans and clustering matter.)
Definition: PostgreSQL: "each level of the tree can be used as a doubly-linked list of pages", and the README: "once we have descended the tree to the correct start point for the scan, the scan looks only at leaf pages and never at higher tree levels". Backward scans (ORDER BY k DESC) use the left-links. Comer: "Sequence set links allow easy sequential processing."
SELECT id FROM orders WHERE id BETWEEN 30 AND 70 ORDER BY id;
1 descend: root -> internal -> leaf L2 (first key >= 30)
2 read L2 from 30 to its end
3 follow right-link to L3, read all
4 follow right-link to L4, read until first key > 70: stop
Index Only Scan using orders_pkey ... Index Cond: ((id >= 30) AND (id <= 70))Real scenarios: keyset pagination (WHERE (created_at, id) > (?, ?) ORDER BY created_at, id LIMIT 50; see Pagination); “orders of the last 24 hours”; MIN/MAX (one descent to the first or last leaf); ORDER BY ... LIMIT without a sort node; merge joins that read two indexes in order.
| Engine | Range scan behaviour |
|---|---|
| PostgreSQL | Index Scan / Index Only Scan both directions; Bitmap Index Scan for many scattered rows; skip scan on multicolumn indexes since PostgreSQL 18 |
| InnoDB | Range on clustered index reads rows directly in PK order; secondary range + PK lookups (MRR batches them) |
| SQL Server | Index Seek with a range predicate, ordered forward or backward |
| SQLite | SEARCH ... USING INDEX (k>? AND k<?) |
| Hash index (PostgreSQL) | Not possible: "Hash indexes support only the = operator" |
Fix: put the range column last in a composite index ((tenant_id, created_at), equality first, range last), and prefer keyset over OFFSET pagination.
Right-most inserts (monotonic keys) vs random UUID inserts Must-know
In plain words: if every new key is larger than all existing keys (an identity column, a timestamp, a UUIDv7), every insert goes to the same last leaf, which fills up and splits cleanly. If keys are random (UUIDv4, hashes), each insert lands on a random leaf somewhere in the index.
Common misunderstanding: “UUIDs are just bigger integers.” The width costs ~40% more index space (16 vs 8 bytes plus tuple overhead), but the randomness is the larger cost: half-empty pages, many more dirty pages per checkpoint, and a working set equal to the whole index instead of its right edge.
Definition: with monotonic keys PostgreSQL uses a right-most split that leaves the old page full to fillfactor (90%) rather than 50/50, and caches the right-most leaf: "We optimize for a common case of insertion of increasing index key values by caching the last page to which this backend inserted the last value, if this page was the rightmost leaf page." InnoDB: "If index records are inserted in a sequential order (ascending or descending), the resulting index pages are about 15/16 full. If records are inserted in a random order, the pages are from 1/2 to 15/16 full." The classic analysis of random insertion gives an average fill of about ln 2 ≈ 69%; the Go model on this page measures 69.6%.
Go teaching tree, 100,000 keys, 64 keys per leaf (go run ./bplustree):
1 sequential keys, 50/50 split height=4 leaves=3124 avg leaf fill=50.0%
2 sequential keys, right-most split height=3 leaves=1563 avg leaf fill=100.0%
3 random keys (UUIDv4-like) height=3 leaves=2245 avg leaf fill=69.6%
PostgreSQL behaves like line 2 with 90% instead of 100% (fillfactor), InnoDB with ~94% (15/16).Real scenarios: switching an events table from UUIDv4 to UUIDv7 primary keys noticeably reduces WAL volume and checkpoint I/O at the same insert rate (fewer distinct pages dirtied, fewer full-page images); an InnoDB table with CHAR(36) UUIDv4 primary key whose insert rate collapses once the table outgrows the buffer pool, because every insert needs a random leaf read; a bigint identity table whose only problem is contention on the one hot right-most page at very high concurrency.
| Key type | Width | Insert pattern | PostgreSQL leaf density | InnoDB effect |
|---|---|---|---|---|
bigint identity / BIGINT AUTO_INCREMENT | 8 B | Right-most append | ~90% (fillfactor) | Pages ~15/16 full, table in insert order |
UUIDv7 (uuidv7() PostgreSQL 18+, Laravel HasUuids) | 16 B | Append (millisecond-ordered) | ~90% | Good if stored as BINARY(16) |
| ULID | 16 B (or 26-char text) | Append | ~90% | Good as BINARY(16) |
UUIDv4 (gen_random_uuid(), uuidv4()) | 16 B | Random leaf | ~69% average, high leaf_fragmentation | Random page splits move rows; secondary indexes carry 16–36 B PK |
| Hash / random token | varies | Random leaf | ~69% | Worst case for a clustered key |
Fix: use bigint generated always as identity or UUIDv7 for primary keys; if you must keep UUIDv4, give the index a lower fillfactor (70–80) and plan periodic REINDEX CONCURRENTLY; in InnoDB never cluster on a random key (use a bigint PK and a secondary unique index on the UUID). Full ID-generation trade-offs are in ID Generation.
B-link trees (Lehman & Yao) and latch coupling Important
In plain words: while one session splits a page, another may be reading down the tree towards that page. A B-link tree lets the reader notice “the key I want has moved to the right” and simply follow a pointer, so readers never need to lock the path from the root.
Common misunderstanding: “Index reads take row locks.” Index pages are protected by short latches (lightweight locks on a buffer, held for microseconds), not by transactional locks. Graefe's survey is built on that distinction; row-level isolation is a different layer (see Locks & Concurrency).
Definition: Lehman & Yao add to each node a high key (upper bound of keys allowed on the page) and a right-link to the next node on the same level. The nbtree README: "Compared to a classic B-tree, L&Y adds a right-link pointer to each page, to the page's right sibling." If a search key exceeds the high key, "the page must've been split concurrently, and you must follow the right-link". Latch coupling (lock coupling, crabbing) is the older alternative: hold the parent latch until the child is latched, then release the parent; Graefe: "This technique is traditionally called" lock coupling "but a better term is" latch coupling. PostgreSQL holds only one page read-latch at a time on the way down; Lehman and Yao "must couple/chain locks as part of moving right" only when inserting the downlink after a split.
Reader R (search 45) Writer W (insert 42 into leaf [30 40 45 50])
1 read parent: 45 -> leaf P
2 latch P exclusively, split: P=[30 40 42], Q=[45 50]
3 P.highkey = 45, P.rightlink = Q (Q reachable before parent knows)
4 release P; later insert separator 45 -> Q into parent
5 latch P (shared): 45 >= P.highkey
6 follow P.rightlink to Q, find 45 -- correct result, no lock on the parent was neededReal scenarios: thousands of concurrent inserts into one table's primary key in PostgreSQL without readers blocking; InnoDB's index latch (index->lock, an SX-latch) and page latches, visible as contention in performance_schema under extreme insert rates; the right-most page being the hottest latch in an append-only table.
| Engine | Concurrency scheme for the tree |
|---|---|
| PostgreSQL | Lehman–Yao B-link tree, page-level read/write latches (buffer content locks), one latch held on descent |
| InnoDB | Page latches with latch coupling plus an index-level SX-latch for structure changes (split/merge) |
| SQL Server | Page latches (PAGELATCH_EX on the last page is the classic “last page insert contention”; OPTIMIZE_FOR_SEQUENTIAL_KEY in SQL Server 2019 and later) |
| SQLite | One writer per database; no page-level concurrency inside the tree |
Fix: nothing to configure in PostgreSQL. For last-page latch contention at extreme rates: SQL Server OPTIMIZE_FOR_SEQUENTIAL_KEY = ON, or spread inserts (hash-partitioned tables, a key prefix), at the cost of losing the append pattern.
Deduplication and posting lists (PostgreSQL 13) Important
In plain words: if the same value appears in many rows (a status or customer_id column), PostgreSQL stores the value once followed by a sorted list of row addresses, instead of repeating the value for every row.
Common misunderstanding: “Indexes on low-cardinality columns are always useless and huge.” Since PostgreSQL 13 they are much smaller; whether the planner uses them is a separate selectivity question (see Query Planning).
Definition: PostgreSQL 13 release notes: "More efficiently store duplicates in B-tree indexes". The manual: deduplication merges "groups of duplicate tuples together, forming a single posting list tuple for each group. The column key value(s) only appear once in this representation." It runs lazily, only when a leaf would otherwise split, and "Deduplication is enabled by default." It cannot be used for numeric, float4/float8, jsonb, nondeterministic collations, container types, or INCLUDE indexes. After pg_upgrade from 12 or older: "Users upgrading with pg_upgrade will need to use REINDEX to make an existing index use this feature."
Leaf page before (PostgreSQL 12): after a deduplication pass (13+):
1 ('paid', (10,1)) ('paid', [(10,1),(10,7),(11,3),(52,9)]) -- one posting list tuple
2 ('paid', (10,7)) ('shipped', [(12,4),(40,2)])
3 ('paid', (11,3))
4 ('paid', (52,9))
5 ('shipped', (12,4)) ('shipped', (40,2)) -- space freed, no page split neededReal scenarios: an index on orders(status) with 5 distinct values shrinks several-fold; a foreign-key index order_items(order_id) with ~10 items per order; a unique index where version churn temporarily creates duplicates of one key (dedup buys time for bottom-up deletion).
| Engine | Duplicate keys in a B-tree index |
|---|---|
| PostgreSQL 13+ | Posting lists (deduplicate_items = on default); visible as tids in bt_page_items |
| PostgreSQL 12 and older | One full index tuple per row (heap TID as tie-breaker since 12) |
| InnoDB | One entry per row; the PK appended makes every secondary entry unique |
| SQL Server | One entry per row (clustering key or RID appended); page/row compression can shrink |
| MongoDB WiredTiger | Index prefix compression removes the repeated prefix |
| PostgreSQL GIN | Posting lists/trees by design (the original inverted-index structure) |
Fix:
CREATE INDEX orders_status_idx ON orders (status); -- dedup on by default
CREATE INDEX title_idx ON films (title) WITH (deduplicate_items = off); -- manual's example to disable it
SELECT allequalimage FROM bt_metap('orders_status_idx'); -- t = dedup is safe for this indexBottom-up index deletion (PostgreSQL 14) Good to know
In plain words: when an UPDATE cannot be HOT, every index on the table gets a new entry, even indexes whose column did not change. PostgreSQL 14 cleans those obsolete "version churn" entries out of a leaf just before it would split, instead of waiting for VACUUM.
Common misunderstanding: “Only VACUUM removes dead index entries.” Since PostgreSQL 14 most garbage in update-heavy indexes is removed by bottom-up deletion; VACUUM is still required, but the index may never grow.
Definition: "B-Tree indexes incrementally delete version churn index tuples by performing bottom-up index deletion passes. Each deletion pass is triggered in reaction to an anticipated" version churn page split. Before it, there was only simple deletion of entries already marked LP_DEAD by passing scans: "Prior to PostgreSQL 14, the only category of B-Tree deletion was simple deletion." The payoff, in the manual's words: "It's quite possible that the on-disk size of certain indexes will never increase by even one single page/block despite constant version churn from UPDATEs."
orders(id pk, status, updated_at, customer_id idx); UPDATE orders SET updated_at = now() WHERE id = 7;
1 updated_at is indexed -> not HOT -> new heap tuple + a new entry in EVERY index (pkey, customer_id idx ...)
2 repeat 1,000 times: customer_id leaf collects 1,000 entries for one logical row
3 leaf full -> before splitting: try simple deletion (LP_DEAD items)
4 then bottom-up: visit the heap for the duplicates, delete entries invisible to all snapshots
5 enough room freed -> no split; index size unchangedReal scenarios: last_seen_at updates on a users table with five indexes; counters updated in place; job tables whose status changes several times per row.
| Engine | Cleaning obsolete index entries |
|---|---|
| PostgreSQL 14+ | Simple deletion + bottom-up deletion at split time; VACUUM for the rest |
| PostgreSQL 13 and older | Simple deletion + VACUUM only |
| InnoDB | Secondary entries delete-marked; purge thread removes them; change buffer may defer |
| SQL Server | Ghost records cleaned by the ghost cleanup task |
Fix: make updates HOT where possible (do not index columns you update constantly; leave heap fillfactor slack); upgrade to 14+ for update-heavy workloads. HOT itself is explained in MVCC, VACUUM & Bloat.
Suffix truncation and prefix compression Good to know
In plain words: a separator in an internal page only has to tell left from right, so it can be shorter than a real key. Suffix truncation drops trailing key columns from separators; prefix compression stores what consecutive keys share only once.
Common misunderstanding: “InnoDB prefix-compresses its index keys.” It does not: InnoDB offers column-prefix indexes (INDEX (email(20)), indexing only the first characters) and page-level compression (ROW_FORMAT=COMPRESSED, zlib); key prefix compression is MyISAM's PACK_KEYS ("When packing binary number keys, MySQL uses prefix compression") and WiredTiger's index default.
Definition: PostgreSQL 12+: "We truncate away suffix key attributes that are not needed for a page high key during a leaf page split." The README states the purpose: "The goal of suffix truncation of key attributes is to improve index fan-out." It works at whole-column granularity (PostgreSQL implements what Bayer and Unterauer call simple prefix B-trees). Comer's example of the idea: between computer and electronic, the separator e suffices. WiredTiger: "Index prefix compression deduplicates common prefixes from indexed fields."
Index on (tenant_id, created_at, id); a leaf splits between
(42, '2026-11-25 10:00:01', 9001) | (43, '2026-01-02 00:00:00', 17)
1 first differing column: tenant_id
2 separator stored in the parent: (43, -inf, -inf) -- 4 bytes of key instead of ~20
3 more separators per internal page -> higher fan-out -> fewer levels
4 in bt_page_items the truncated columns are simply absent ("minus infinity")Real scenarios: composite indexes that lead with a low-cardinality column (tenant_id); indexes with INCLUDE payload columns (always truncated from pivots); MongoDB compound indexes on long string prefixes.
| Engine | Separator shortening | Key prefix compression |
|---|---|---|
| PostgreSQL 12+ | Suffix truncation of whole trailing columns (and heap TID) | No (deduplication instead) |
| MySQL InnoDB | No | No; column-prefix indexes and ROW_FORMAT=COMPRESSED page compression |
| MySQL MyISAM | No | PACK_KEYS (prefix compression) |
| MongoDB WiredTiger | n/a | Index prefix compression on by default |
| SQL Server | No | DATA_COMPRESSION = PAGE includes prefix and dictionary compression |
| Oracle | No | COMPRESS n / advanced index compression |
Fix: order composite index columns so the distinguishing column comes early in the place where splits happen; use INCLUDE (...) for payload columns instead of adding them to the key.
Clustered B+tree table vs heap table, and what a secondary index stores Must-know
In plain words: PostgreSQL keeps rows in an unordered heap and every index (primary key included) points into it with a physical address (TID). InnoDB stores the table as the primary-key B+tree; secondary indexes point to rows by primary-key value.
Common misunderstanding: “The primary key index in PostgreSQL is the table, like in MySQL.” It is an ordinary B-tree beside the heap. CLUSTER reorders the heap once; it does not keep it ordered.
Definition: InnoDB: "In InnoDB, each record in a secondary index contains the primary key columns for the row, as well as the columns specified for the secondary index." and "If the primary key is long, the secondary indexes use more space, so it is advantageous to have a short primary key." Without a primary key or a NOT NULL unique key InnoDB creates GEN_CLUST_INDEX on a hidden 6-byte row ID. PostgreSQL leaf tuples hold the key plus a 6-byte heap TID (block number, line pointer); see Database Internals.
SELECT name FROM users WHERE email = 'ann@x.io';
PostgreSQL (heap) InnoDB (clustered)
1 descend users_email_idx (3-4 pages) descend idx_email (3-4 pages)
2 leaf: TID (812,4) leaf: PK id = 7
3 read heap page 812, item 4 descend PRIMARY by id = 7 (3-4 pages, upper levels cached)
4 visibility check on the heap tuple row is in the clustered leaf; MVCC via undo if needed
PK range scan: index + heap pages PK range scan: clustered leaves only (rows already in order)Real scenarios: an InnoDB table with a CHAR(36) UUID primary key and six secondary indexes, where the secondary indexes are bigger than the table; a PostgreSQL table where updating any indexed column writes a new entry in every index (non-HOT update), while InnoDB updates only the secondary indexes whose columns changed; time-range scans on an InnoDB table clustered by (device_id, ts) that read contiguous pages.
| Aspect | PostgreSQL (heap + B-tree) | MySQL InnoDB (clustered B+tree) |
|---|---|---|
| Row location | Heap page; index stores 6-byte TID | Primary-key leaf |
| Secondary entry | key + TID (or posting list) | key + full primary key |
| Cost of a wide PK | Only the PK index grows | Every secondary index grows |
| PK range scan | Index + scattered heap pages (unless correlated) | Contiguous leaves |
| Secondary lookup | 1 index descent + 1 heap page | 2 descents (secondary, then clustered) |
| Row moves on update | New tuple version, new TID; HOT avoids index writes | Row stays in PK leaf; secondaries change only if their columns change |
| Random PK inserts | Index pages split; heap still appends | Table pages split; rows move |
| Index-only scan | Needs visibility map all-visible pages | Covering secondary index (PK columns are free) |
| Other engines | Table layout |
|---|---|
| SQL Server | Clustered index (B+tree) or heap (RID pointers); nonclustered entries carry the clustering key, or RID on a heap |
| Oracle | Heap by default (ROWID); index-organized tables (IOT) are clustered B+trees |
| SQLite | Rowid tables are table b-trees keyed by rowid; WITHOUT ROWID tables are clustered on the PK (index b-tree) |
| MongoDB WiredTiger | Collection B-tree keyed by an internal RecordId; indexes point to RecordId (clustered collections are also available) |
Fix: in InnoDB keep the PK short and monotonic (BIGINT UNSIGNED AUTO_INCREMENT, or UUIDv7 as BINARY(16)); in PostgreSQL the PK type matters for that one index and for foreign keys, and covering indexes need VACUUM to keep the visibility map current.
Index size estimation Important
In plain words: an index is roughly “number of entries × (key size + overhead) ÷ page fill”. You can predict it before you build it.
Common misunderstanding: “A bigint index costs 8 bytes per row.” In PostgreSQL each entry is an 8-byte index tuple header plus the 8-byte key (16 bytes, MAXALIGNed) plus a 4-byte line pointer: 20 bytes, then divided by the fill (90%).
Definition: PostgreSQL leaf usable space = 8192 − 24 (page header) − 16 (B-tree special space) = 8,152 bytes. Entries per leaf = usable × fill ÷ (tuple + 4). Size ≈ entries ÷ per-leaf × 8 kB × ~1.003 (internal pages).
1 bigint: tuple 16 B -> 8152 / 20 = 407 max, 366 at 90% -> 1e8 rows: 272,480 leaves = 2.2 GB
2 uuid: tuple 24 B -> 8152 / 28 = 291 max, 262 at 90% -> 1e8 rows: 381,680 leaves = 3.1 GB
3 uuid v4 random fill ~69%: ~201 per leaf -> 1e8 rows: ~500,000 leaves = ~4.1 GB
4 text ~32 B: tuple 40 B -> 185 max, 166 at 90%
5 InnoDB secondary on a 30-byte email + PK: bigint ~44 B/entry, BINARY(16) ~52 B, CHAR(36) utf8mb4 ~72 BReal scenarios: capacity planning for a 2-billion-row table (each bigint index ≈ 45 GB, each uuid index ≈ 62–82 GB); deciding whether an index fits in RAM; spotting bloat (actual size 2× estimate).
| Engine | How to measure |
|---|---|
| PostgreSQL | pg_relation_size('idx'), pg_size_pretty(pg_indexes_size('t')), pgstatindex('idx') |
| MySQL InnoDB | mysql.innodb_index_stats (stat_name = 'size', n_leaf_pages), INFORMATION_SCHEMA.TABLES.INDEX_LENGTH |
| SQL Server | sys.dm_db_index_physical_stats (avg_page_space_used_in_percent) |
| SQLite | dbstat virtual table, sqlite3_analyzer |
Fix: compare measured size with the estimate; above ~1.5× investigate density with pgstatindex.
Index bloat and REINDEX Must-know
In plain words: pages that split and then lost rows stay half empty. Over time the index is far bigger than its contents and range scans read more pages than necessary. Rebuilding it packs pages again.
Common misunderstanding: “VACUUM FULL or autovacuum shrinks indexes.” Plain VACUUM removes dead entries and recycles empty pages but never compacts half-empty ones; VACUUM FULL rewrites the table and its indexes under an ACCESS EXCLUSIVE lock, which is rarely acceptable online.
Definition: index bloat = actual size ÷ ideal size. Causes: 50/50 splits from random keys, mass deletes, non-HOT update churn (before PostgreSQL 14 especially), long-running transactions that keep dead entries alive. REINDEX INDEX CONCURRENTLY (PostgreSQL 12+) builds a new copy without blocking writes and swaps it in.
1 SELECT avg_leaf_density, leaf_fragmentation FROM pgstatindex('orders_pkey'); -- 41.2 | 48.0
2 REINDEX INDEX CONCURRENTLY orders_pkey; -- builds orders_pkey_ccnew, waits for old snapshots, swaps
3 SELECT avg_leaf_density, leaf_fragmentation FROM pgstatindex('orders_pkey'); -- ~90 | ~0
4 if it fails midway: an INVALID index named *_ccnew remains; DROP INDEX CONCURRENTLY it and retryReal scenarios: a UUIDv4 primary key at 45% density after a year; a soft-delete purge that removed 60% of rows; an index on status from PostgreSQL 12 upgraded with pg_upgrade (no deduplication until REINDEX).
| Engine | Online rebuild | Notes |
|---|---|---|
| PostgreSQL | REINDEX INDEX CONCURRENTLY, REINDEX TABLE CONCURRENTLY | Two passes, waits for old transactions; pg_repack rebuilds table + indexes online |
| MySQL InnoDB | OPTIMIZE TABLE (= ALTER TABLE ... FORCE, online DDL) | Rebuilds clustered + secondary indexes with sorted index builds at innodb_fill_factor |
| SQL Server | ALTER INDEX ... REBUILD WITH (ONLINE = ON) / REORGANIZE | Online rebuild is an Enterprise feature |
| SQLite | REINDEX, VACUUM | Single-writer database: blocking |
Fix: the Laravel command in Laravel flags indexes below a density threshold; rebuild them in a maintenance window or concurrently.
B-tree vs hash index, and B-tree vs LSM-tree Good to know
In plain words: a hash index answers only "equal to"; a B-tree answers equality, ranges, ordering and prefixes. An LSM-tree trades read cost for cheaper writes by never updating pages in place.
Common misunderstanding: “Hash is O(1), so it always beats a B-tree for equality.” The B-tree's O(log n) is 3–4 cached page reads; the PostgreSQL hash index wins mainly on size for long keys ("hash indexes may be much smaller than B-trees when indexing longer data items such as UUIDs, URLs"), and cannot enforce uniqueness, sort, or serve ranges.
Definition: PostgreSQL hash index: "Hash indexes support only the = operator, so WHERE clauses that specify range operations will not be able to take advantage of hash indexes." and "Hash indexes support only single-column indexes and do not allow uniqueness checking." An LSM-tree buffers writes in memory, flushes sorted immutable files and compacts them, turning random writes into sequential ones; B-trees update pages in place and pay write amplification on every split and every full-page write. Both are compared in depth in Storage Engines.
Insert 1 row into a table with 5 B-tree indexes (PostgreSQL, non-HOT):
1 heap page write + 5 index leaf writes (each a random page, possibly a split = 3+ pages)
2 WAL: 6+ records, plus a full-page image for each page first touched after a checkpoint
-> write amplification: one 150-byte row can cause tens of kB of WAL
Same insert into an LSM engine (RocksDB/MyRocks, Cassandra, CockroachDB Pebble):
1 append to WAL + memtable (sequential)
2 later flushed and compacted several times (amplification moves to compaction)Real scenarios: a URL-shortener lookup by 200-byte URL (hash index or B-tree on a hash); time-series ingestion at 500k rows/s (LSM or columnar); OLTP with mixed reads and range queries (B-tree).
| Need | B-tree | Hash (PostgreSQL) | LSM (RocksDB, Cassandra, Pebble) |
|---|---|---|---|
| Equality | Yes | Yes | Yes (Bloom filters avoid useless reads) |
| Range / ORDER BY / prefix LIKE | Yes | No | Yes (merge of sorted runs) |
| Unique constraint | Yes | No | Engine-specific |
| Write cost | In-place page writes, splits | In-place bucket writes, splits | Sequential writes, compaction later |
| Read cost | h pages | ~1–2 pages | Several sorted runs per lookup |
Fix: default to B-tree; consider hash for equality-only lookups on long keys; consider an LSM engine only when write throughput dominates (see Storage Engines).
Per-engine behaviour
What each database really builds
| Product | Index structure | Table layout | Page size | Fill / split policy |
|---|---|---|---|---|
| PostgreSQL | nbtree: B+tree, Lehman–Yao B-link, dedup (13+), bottom-up deletion (14+), suffix truncation (12+), skip scan (18+) | Heap + TIDs | 8 kB | fillfactor 90; right-most split keeps left page at fillfactor |
| MySQL InnoDB | B+tree for clustered and secondary indexes; R-tree for spatial | Clustered on PK (or GEN_CLUST_INDEX) | 16 kB default | 1/16 free; sorted builds at innodb_fill_factor; merge below MERGE_THRESHOLD |
| MySQL MyISAM | B-tree with PACK_KEYS prefix compression | Heap file (.MYD) | key cache blocks (myisam_block_size) | n/a (legacy engine) |
| SQL Server | B+tree ("Rowstore indexes are organized as B+ trees") | Clustered index or heap | 8 kB | FILLFACTOR, PAD_INDEX; OPTIMIZE_FOR_SEQUENTIAL_KEY |
| Oracle | B+tree-style index | Heap (ROWID) or IOT | 8 kB default block | PCTFREE; special right-most split for increasing keys |
| SQLite | Index b-tree (classic B-tree) and table b-tree (data in leaves) | Rowid table or WITHOUT ROWID | 4 kB default | Rebalancing among siblings |
| MongoDB WiredTiger | B+tree-style pages, prefix compression on indexes | Collection B-tree keyed by RecordId | variable (internal_page_max/leaf_page_max) | Pages reconciled on eviction |
| CockroachDB | No B-tree on disk: Pebble LSM; secondary indexes are KV ranges | Clustered on PK (KV) | n/a | Ranges split by size and load |
| Redis | No B-tree; sorted sets use a skiplist + hash | In memory | n/a | n/a |
Feature × engine
| Feature | PostgreSQL | InnoDB | SQL Server | SQLite |
|---|---|---|---|---|
| Leaves linked both ways | Yes | Yes | Yes | No sibling pointers |
| Duplicate compression | Deduplication (posting lists) | No | Page compression | No |
| Separator shortening | Suffix truncation | No | No | No |
| Covering payload columns | INCLUDE | PK columns implicit | INCLUDE | No (WITHOUT ROWID clusters) |
| Online rebuild | REINDEX CONCURRENTLY | OPTIMIZE TABLE (online DDL) | REBUILD WITH (ONLINE = ON) | No |
| Inspect pages | pageinspect | innodb_ruby (third-party), INNODB_METRICS | DBCC PAGE (undocumented) | dbstat |
Mechanics
Inside a PostgreSQL B-tree page Important
Every index page uses the standard page layout: a 24-byte page header, an array of 4-byte line pointers growing forward, index tuples growing backward from the end, and a 16-byte special area (BTPageOpaqueData: left/right sibling block numbers btpo_prev/btpo_next, level, flags). Block 0 is the metapage ("A single metapage is stored in a fixed position at the start of the first segment file of the index") holding the root block and level (bt_metap). On every page except the right-most of its level, item 1 is the high key, "meaning its data serves as an upper bound on all items appearing on the page". Tuples in internal pages are pivot tuples: separator + downlink; the first data item of an internal page "reliably has every column truncated away" (it means minus infinity). Heap TID is a hidden tie-breaker key column since PostgreSQL 12, so every key is unique on its level.
bt_page_items('orders_pkey', 1) on a non-rightmost leaf (illustrative values):
itemoffset | ctid | itemlen | data | htid | tids
1 | (3,1) | 16 | 6f 01 00 00 00 00 00 00 | | <- high key (upper bound)
2 | (0,1) | 16 | 01 00 00 00 00 00 00 00 | (0,1) | <- key 1 -> heap block 0, item 1
3 | (0,2) | 16 | 02 00 00 00 00 00 00 00 | (0,2) |
...The Lehman–Yao invariants in PostgreSQL Good to know
- Keys in a subtree S satisfy
Ki < v <= Ki+1for the adjacent separators Ki, Ki+1 in the parent; uniqueness via heap TID makes the strict inequality hold. - A split first creates the right sibling and right-link, then inserts the downlink in the parent; between the two steps the new page is reachable only through the right-link, which is legal.
- PostgreSQL deviates from the paper in one documented way: Lehman and Yao "assume that in-memory copies of tree pages are unshared", but PostgreSQL shares buffers, so "we do page-level read locking on btree pages in order to guarantee that no record is modified while we are examining it."
- Deleted pages are recycled only after no scan can still hold a pointer to them (the "drain technique").
- The right-most page of a level is never deleted.
Split point choice Good to know
PostgreSQL (12+) chooses the leaf split point to maximise suffix truncation without unbalancing the halves; for duplicates it "goes to great lengths to avoid having duplicates span more than one page"; for a right-most insert it uses the fillfactor-based split (left page left at 90%). Internal page splits prefer the smallest separator within an acceptable range, which keeps short pivots near the root. InnoDB detects sequential inserts per page (last insert position and direction) and splits at the insertion point instead of the middle; SQL Server and Oracle also special-case right-most inserts.
Knobs Must-know
| Knob | Engine | Default | Effect |
|---|---|---|---|
fillfactor (index) | PostgreSQL | 90 | Leaf fill at build and right-most appends |
deduplicate_items | PostgreSQL 13+ | on | Posting lists for duplicates |
fillfactor (table) | PostgreSQL | 100 | Heap slack for HOT updates (fewer index entries) |
random_page_cost / seq_page_cost | PostgreSQL | 4 / 1 | Planner's view of random vs sequential I/O |
shared_buffers, effective_cache_size | PostgreSQL | 128 MB / 4 GB | Cache size and planner's cache assumption |
innodb_page_size | InnoDB | 16k | Page (node) size, fixed at initialisation |
innodb_fill_factor | InnoDB | 100 | Sorted index build fill (1/16 always kept) |
MERGE_THRESHOLD | InnoDB | 50 | Page merge trigger, per table or index via COMMENT |
innodb_buffer_pool_size | InnoDB | 128 MB | Cache for all index pages |
FILLFACTOR, PAD_INDEX, OPTIMIZE_FOR_SEQUENTIAL_KEY | SQL Server | 0 (100), OFF, OFF | Build fill, internal page fill, last-page contention |
PRAGMA page_size, PRAGMA cache_size | SQLite | 4096, -2000 (2 MB) | Node size, cache |
storage.wiredTiger.indexConfig.prefixCompression | MongoDB | true | Index prefix compression |
Messages and limits you will meet Important
| Message | Engine | Meaning |
|---|---|---|
index row size 2720 exceeds btree version 4 maximum 2704 for index "..." (SQLSTATE 54000) | PostgreSQL | An entry must fit in about a third of a page; index a hash or prefix instead |
Specified key was too long; max key length is 3072 bytes (error 1071) | MySQL InnoDB | Index key prefix limit for DYNAMIC/COMPRESSED rows on 16 kB pages |
index "..." contains unexpected zero page / contains corrupted page | PostgreSQL | Corruption: REINDEX it, check amcheck (bt_index_check) |
could not create unique index ... Key (...) is duplicated. (23505) | PostgreSQL | CREATE UNIQUE INDEX / REINDEX found duplicates (e.g. after collation changes) |
INVALID index after CREATE/REINDEX ... CONCURRENTLY fails | PostgreSQL | \d shows INVALID; drop and rebuild |
Solving the classic problems
Random UUID primary keys
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| UUIDv7 | DEFAULT uuidv7() (PostgreSQL 18+), Laravel HasUuids (generates v7) | Append pattern, globally unique, no coordination | Leaks creation time; 16 B key |
| bigint identity + public UUID | bigint PK, uuid unique secondary column | Smallest PK and FKs; UUID for URLs | Two indexes; the UUID index still random if v4 |
| Keep UUIDv4, lower fillfactor | WITH (fillfactor = 70) + periodic REINDEX CONCURRENTLY | No schema change | Treats the symptom |
InnoDB: BINARY(16) | UUID_TO_BIN(UUID(), 1) for v1, raw bytes for v7 | 16 B instead of 36+ B in every secondary | Application conversion |
-- PostgreSQL 18+
CREATE TABLE orders (
id uuid PRIMARY KEY DEFAULT uuidv7(),
customer_id bigint NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
-- or the smallest option
CREATE TABLE orders2 (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
public_id uuid NOT NULL DEFAULT uuidv7() UNIQUE,
customer_id bigint NOT NULL
);
-- MySQL 8.4 InnoDB
CREATE TABLE orders (
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
public_id BINARY(16) NOT NULL UNIQUE,
customer_id BIGINT UNSIGNED NOT NULL,
KEY idx_customer (customer_id)
) ENGINE=InnoDB;A bloated index
CREATE EXTENSION IF NOT EXISTS pgstattuple;
SELECT c.relname, pg_size_pretty(pg_relation_size(c.oid)) AS size,
s.avg_leaf_density, s.leaf_fragmentation
FROM pg_class c
JOIN pg_index i ON i.indexrelid = c.oid
JOIN pg_am am ON am.oid = c.relam AND am.amname = 'btree'
CROSS JOIN LATERAL pgstatindex(c.oid::regclass) s
WHERE c.relnamespace = 'public'::regnamespace
ORDER BY pg_relation_size(c.oid) DESC LIMIT 20;
REINDEX INDEX CONCURRENTLY orders_pkey; -- PostgreSQL 12+
-- MySQL: OPTIMIZE TABLE orders; (InnoDB maps it to ALTER TABLE ... FORCE, online)Wide primary key in InnoDB
Every secondary entry carries the PK. A CHAR(36) utf8mb4 UUID PK makes a 30-byte email secondary entry ~72 bytes instead of ~44 with BIGINT: about 207 instead of 333 entries per 16 kB page, so the secondary index is ~60% larger and one level deeper sooner. Fix: BIGINT PK and the UUID as a BINARY(16) unique secondary key.
Range queries that read too many pages
-- Equality first, range last, payload in INCLUDE: one descent, contiguous leaves, no heap visits
CREATE INDEX orders_customer_created_idx ON orders (customer_id, created_at) INCLUDE (total);
EXPLAIN (ANALYZE, BUFFERS)
SELECT created_at, total FROM orders
WHERE customer_id = 42 AND created_at >= now() - interval '30 days'
ORDER BY created_at;
-- Index Only Scan using orders_customer_created_idx ... Heap Fetches: 0Low-cardinality index too big
On PostgreSQL 13+ check deduplication is active (bt_metap(...).allequalimage = t, and tids arrays in bt_page_items); after a pg_upgrade from 12, REINDEX. If the planner never uses it, a partial index (WHERE status = 'pending') is usually the real fix (Indexing).
Go
Example: a teaching B+tree
A stdlib-only, in-memory B+tree with copy-up leaf splits, push-up internal splits, linked leaves and a range scan. It runs three insert patterns and checks that the leaf-chain scan returns every key in order. The rightmost flag implements the append-friendly split rule that PostgreSQL, InnoDB, SQL Server and Oracle use.
// A teaching in-memory B+tree: keys and values live only in leaves, leaves
// are linked left-to-right for range scans, and internal nodes hold
// separator keys only. One node stands for one disk page.
package main
import (
"fmt"
"math/rand/v2"
"sort"
)
type node struct {
leaf bool
keys []int
vals []string // leaf only
kids []*node // internal only: len(kids) == len(keys)+1
next *node // leaf only: right sibling (the "sequence set" link)
}
// Tree is a B+tree whose nodes hold at most max keys.
type Tree struct {
root *node
max int
rightmost bool // PostgreSQL/InnoDB-style: keep the left page full on an append split
height int
splits int
}
// New returns an empty tree; rightmost enables the append-friendly split rule.
func New(maxKeys int, rightmost bool) *Tree {
return &Tree{root: &node{leaf: true}, max: maxKeys, rightmost: rightmost, height: 1}
}
// childIndex returns the child that may contain key: separators equal to
// the key route right, because a split copies the first right key up.
func childIndex(n *node, key int) int {
return sort.Search(len(n.keys), func(i int) bool { return n.keys[i] > key })
}
// Get descends from the root to one leaf: height page reads.
func (t *Tree) Get(key int) (string, bool) {
n := t.root
for !n.leaf {
n = n.kids[childIndex(n, key)]
}
i := sort.SearchInts(n.keys, key)
if i < len(n.keys) && n.keys[i] == key {
return n.vals[i], true
}
return "", false
}
// Put inserts or replaces key; a split of the root adds a level.
func (t *Tree) Put(key int, val string) {
sep, right := t.insert(t.root, key, val, true)
if right != nil {
t.root = &node{keys: []int{sep}, kids: []*node{t.root, right}}
t.height++
}
}
// splitAt picks the split point: the middle, or "everything stays left"
// when the new key was appended at the end of the right-most node.
func (t *Tree) splitAt(n *node, pos int, isRightmost bool) int {
if t.rightmost && isRightmost && pos == len(n.keys)-1 {
return len(n.keys) - 1
}
return len(n.keys) / 2
}
func (t *Tree) insert(n *node, key int, val string, isRightmost bool) (int, *node) {
if n.leaf {
i := sort.SearchInts(n.keys, key)
if i < len(n.keys) && n.keys[i] == key {
n.vals[i] = val
return 0, nil
}
n.keys = append(n.keys[:i], append([]int{key}, n.keys[i:]...)...)
n.vals = append(n.vals[:i], append([]string{val}, n.vals[i:]...)...)
if len(n.keys) <= t.max {
return 0, nil
}
t.splits++
mid := t.splitAt(n, i, isRightmost)
right := &node{leaf: true, next: n.next}
right.keys = append([]int(nil), n.keys[mid:]...)
right.vals = append([]string(nil), n.vals[mid:]...)
n.keys, n.vals, n.next = n.keys[:mid:mid], n.vals[:mid:mid], right
return right.keys[0], right // copy up: the key also stays in the leaf
}
ci := childIndex(n, key)
sep, child := t.insert(n.kids[ci], key, val, isRightmost && ci == len(n.kids)-1)
if child == nil {
return 0, nil
}
n.keys = append(n.keys[:ci], append([]int{sep}, n.keys[ci:]...)...)
n.kids = append(n.kids[:ci+1], append([]*node{child}, n.kids[ci+1:]...)...)
if len(n.keys) <= t.max {
return 0, nil
}
t.splits++
mid := t.splitAt(n, ci, isRightmost)
up := n.keys[mid] // push up: an internal separator moves, it is not copied
right := &node{}
right.keys = append([]int(nil), n.keys[mid+1:]...)
right.kids = append([]*node(nil), n.kids[mid+1:]...)
n.keys, n.kids = n.keys[:mid:mid], n.kids[:mid+1:mid+1]
return up, right
}
// Range calls fn for every key in [lo, hi]: one descent, then leaf links.
func (t *Tree) Range(lo, hi int, fn func(k int, v string)) {
n := t.root
for !n.leaf {
n = n.kids[childIndex(n, lo)]
}
for ; n != nil; n = n.next {
for i, k := range n.keys {
if k > hi {
return
}
if k >= lo {
fn(k, n.vals[i])
}
}
}
}
// leafStats walks the leaf chain like pgstatindex walks leaf pages.
func (t *Tree) leafStats() (leaves int, fill float64) {
n := t.root
for !n.leaf {
n = n.kids[0]
}
keys := 0
for ; n != nil; n = n.next {
leaves++
keys += len(n.keys)
}
return leaves, 100 * float64(keys) / float64(leaves*t.max)
}
func run(name string, keys []int, rightmost bool) {
t := New(64, rightmost)
for _, k := range keys {
t.Put(k, fmt.Sprintf("row-%d", k))
}
leaves, fill := t.leafStats()
prev, count := -1, 0
t.Range(0, len(keys), func(k int, _ string) {
if k <= prev {
panic("range scan out of order")
}
prev, count = k, count+1
})
if count != len(keys) {
panic(fmt.Sprintf("range scan saw %d of %d keys", count, len(keys)))
}
v, ok := t.Get(keys[len(keys)/2])
fmt.Printf("%-28s height=%d leaves=%5d splits=%5d avg leaf fill=%5.1f%% get=%s/%v\n",
name, t.height, leaves, t.splits, fill, v, ok)
}
func main() {
const n = 100_000
seq := make([]int, n)
for i := range seq {
seq[i] = i + 1 // bigint identity / UUIDv7: always the right-most leaf
}
rnd := rand.New(rand.NewPCG(1, 2)).Perm(n) // UUIDv4: anywhere in the tree
for i := range rnd {
rnd[i]++
}
run("sequential, 50/50 split", seq, false)
run("sequential, right-most split", seq, true)
run("random, 50/50 split", rnd, false)
t := New(4, true)
for _, k := range []int{10, 20, 30, 40, 50, 25, 35, 5} {
t.Put(k, "")
}
got := []int{}
t.Range(20, 40, func(k int, _ string) { got = append(got, k) })
fmt.Println("range [20,40] on a tiny tree:", got)
}Output (go run ./bplustree, Go 1.24+):
sequential, 50/50 split height=4 leaves= 3124 splits= 3217 avg leaf fill= 50.0% get=row-50001/true
sequential, right-most split height=3 leaves= 1563 splits= 1586 avg leaf fill=100.0% get=row-50001/true
random, 50/50 split height=3 leaves= 2245 splits= 2297 avg leaf fill= 69.6% get=row-42935/true
range [20,40] on a tiny tree: [20 25 30 35 40]The Go angle
Go's standard library has no ordered map; sort.Search over a slice is the building block, which is exactly what one B+tree node does. For production in-memory ordered indexes, github.com/google/btree (a B-tree with generics) and github.com/tidwall/btree are the common choices; embedded databases written in Go use page-based trees too: bbolt (go.etcd.io/bbolt) is a B+tree with copy-on-write pages, while Pebble and BadgerDB are LSM engines. Against PostgreSQL, pgx simply runs the SQL on this page (SELECT * FROM pgstatindex($1)); the interesting Go-side decision is the key you generate: github.com/google/uuid offers uuid.NewV7() for append-friendly keys.
Laravel
Example: three key choices in one migration
<?php
// database/migrations/2026_11_25_000000_create_order_key_variants.php
// Three copies of the same table that differ only in the primary key, so the
// page-split behaviour of each key choice can be compared with pgstatindex.
// PostgreSQL 18+ (uuidv7() is new in 18; uuidv4() is an alias of gen_random_uuid()).
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Query\Expression;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
// 1) bigint identity: 8-byte key, always appended at the right-most leaf.
// generatedAs()->always() gives "bigint generated always as identity".
Schema::create('orders_bigint', function (Blueprint $table) {
$table->id()->generatedAs()->always();
$table->unsignedBigInteger('customer_id')->index();
$table->timestampTz('created_at')->useCurrent();
});
// 2) UUID v4: 16-byte random key, lands on a random leaf -> 50/50 splits.
Schema::create('orders_uuid4', function (Blueprint $table) {
$table->uuid('id')->primary()->default(new Expression('uuidv4()'));
$table->unsignedBigInteger('customer_id')->index();
$table->timestampTz('created_at')->useCurrent();
});
// 3) UUID v7: 16-byte key whose first 48 bits are a millisecond
// timestamp, so new keys sort after old ones (append pattern).
Schema::create('orders_uuid7', function (Blueprint $table) {
$table->uuid('id')->primary()->default(new Expression('uuidv7()'));
$table->unsignedBigInteger('customer_id')->index();
$table->timestampTz('created_at')->useCurrent();
});
// MySQL/InnoDB note: uuid() maps to CHAR(36) there. Every secondary
// index stores the primary key, so prefer BINARY(16) (UUID_TO_BIN with
// swap_flag = 1 for v1, or raw bytes for v7) or a bigint key.
}
public function down(): void
{
Schema::dropIfExists('orders_uuid7');
Schema::dropIfExists('orders_uuid4');
Schema::dropIfExists('orders_bigint');
}
};The Eloquent model: HasUuids generates UUIDv7 in Laravel 13 ("By default, the HasUuids trait will generate UUIDv7 identifiers for your models. These UUIDs are more efficient for indexed database storage because they can be sorted lexicographically."); HasVersion4Uuids is the opt-in for random v4.
<?php
// app/Models/Order.php — Eloquent generates the key in PHP before INSERT.
// HasUuids produces UUIDv7 (time-ordered) in Laravel 13; switch to
// HasVersion4Uuids only if you really need fully random identifiers.
namespace App\Models;
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Model;
class Order extends Model
{
use HasUuids; // Str::uuid7(): appends near the right-most leaf
protected $table = 'orders_uuid7';
public $timestamps = false;
protected $fillable = ['customer_id'];
}Example: an index-health Artisan command
<?php
// app/Console/Commands/IndexStatsCommand.php
// php artisan db:index-stats orders_uuid4 --min-density=70
// Reads pgstatindex() (extension pgstattuple) for every B-tree index of a
// table and flags indexes whose leaves are sparse enough to justify
// REINDEX INDEX CONCURRENTLY.
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class IndexStatsCommand extends Command
{
protected $signature = 'db:index-stats {table} {--min-density=70}';
protected $description = 'Show B-tree height, size, leaf density and fragmentation (PostgreSQL)';
public function handle(): int
{
if (DB::getDriverName() !== 'pgsql') {
$this->error('pgstatindex() exists only in PostgreSQL.');
return self::FAILURE;
}
// Needs a role allowed to create extensions, or run it once in a migration.
DB::statement('CREATE EXTENSION IF NOT EXISTS pgstattuple');
$indexes = DB::select(<<<'SQL'
SELECT c.relname AS name
FROM pg_index i
JOIN pg_class c ON c.oid = i.indexrelid
JOIN pg_am am ON am.oid = c.relam
WHERE i.indrelid = ?::regclass AND am.amname = 'btree'
ORDER BY c.relname
SQL, [$this->argument('table')]);
$minDensity = (float) $this->option('min-density');
$rows = [];
foreach ($indexes as $index) {
$s = DB::selectOne(
'SELECT tree_level, index_size, internal_pages, leaf_pages,
avg_leaf_density, leaf_fragmentation
FROM pgstatindex(?::regclass)',
[$index->name],
);
$rows[] = [
$index->name,
$s->tree_level + 1, // levels = root level + 1
number_format($s->index_size / 1024 / 1024, 1).' MB',
$s->internal_pages,
$s->leaf_pages,
$s->avg_leaf_density,
$s->leaf_fragmentation,
$s->avg_leaf_density < $minDensity ? 'REINDEX CONCURRENTLY' : 'ok',
];
}
$this->table(
['index', 'levels', 'size', 'internal', 'leaf', 'leaf density %', 'leaf frag %', 'advice'],
$rows,
);
return self::SUCCESS;
}
}The Laravel angle
$table->id() is an alias of bigIncrements (a bigserial on PostgreSQL); adding ->generatedAs()->always() produces a SQL-standard identity column. $table->uuid('id') is a native uuid on PostgreSQL but CHAR(36) on MySQL, which is the worst case for InnoDB secondary indexes; for MySQL prefer id() plus a binary('public_id', length: 16, fixed: true) unique column (without fixed: true it is VARBINARY(16)), or accept the cost knowingly. HasUlids (26-character ULIDs) is also time-ordered. Index options such as fillfactor or INCLUDE have no Blueprint method: use DB::statement('CREATE INDEX ... WITH (fillfactor = 70)') in the migration, and run REINDEX ... CONCURRENTLY outside a transaction (set public $withinTransaction = false; on the migration, because PostgreSQL refuses CONCURRENTLY inside a transaction block).
Choosing
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| New OLTP table, PostgreSQL | bigint GENERATED ALWAYS AS IDENTITY PK | uuidv7() public id if needed | Smallest key, right-most inserts |
| New OLTP table, InnoDB | BIGINT UNSIGNED AUTO_INCREMENT PK | UUID as BINARY(16) unique key | Every secondary index carries the PK |
| Need client-generated or merge-safe IDs | UUIDv7 / ULID | Store as uuid / BINARY(16) | Append pattern without coordination |
| Existing UUIDv4 PK, can't change | Keep | fillfactor 70–80, scheduled REINDEX CONCURRENTLY | Absorbs random splits |
| Static lookup table | Default index | fillfactor = 100 | Never splits |
| Update-heavy table (PostgreSQL) | Fewer indexes on hot columns | Table fillfactor 80–90 for HOT, PostgreSQL 14+ | Bottom-up deletion + HOT keep indexes small |
| Low-cardinality column | B-tree with dedup (PG 13+) or partial index | Check planner usage | Size vs selectivity |
| Equality on long keys (URLs, tokens) | Hash index or B-tree on md5() | Unique via B-tree on hash | B-tree on long keys is deep and large |
| Range/sort queries | B-tree, equality columns first, range last | INCLUDE for index-only scans | Leaf-chain scan |
| Very high insert rate, append-only | B-tree with monotonic key, or LSM/columnar | Partition by time | Right-most page contention, WAL volume |
| Index density below ~60% | REINDEX INDEX CONCURRENTLY / OPTIMIZE TABLE | pg_repack for table + indexes | Restore density and cache efficiency |
In architecture: from a single process to a distributed system
A B-tree is a single-node structure: it lives in one database's pages. Architecture decides which keys it receives, how many indexes each write must maintain, and where the hot pages are.
Monolith: one process, one database
How it shows up: every table has a PK index and a handful of secondaries; every request is a few point lookups and range scans. Key choice and index count drive write cost and cache footprint.
Simplest correct usage: bigint identity keys, an index per real query pattern (equality first, range last), no duplicate or unused indexes (pg_stat_user_indexes.idx_scan = 0), and an index-health check in CI or a scheduled command.
Example (simple): a Laravel shop with orders(id bigint), orders(customer_id, created_at) and order_items(order_id). All lookups are 3–4 page reads; the customer history page is one range scan.
Example (complex): the same shop exposes order IDs in URLs and wants unguessable IDs. Instead of a UUIDv4 PK (random splits on the hottest table plus 16-byte FKs in order_items, payments, shipments), it keeps the bigint PK and adds public_id uuid DEFAULT uuidv7() UNIQUE: one extra index, still append-friendly.
Modular monolith / multiple databases
How it shows up: modules own their tables; IDs cross module boundaries as references. If modules may later move to separate databases, IDs must be generatable without a shared sequence.
Example: Billing stores order_ref uuid referring to Orders. Using UUIDv7 everywhere gives each module append-friendly indexes and lets data be merged or moved later without key collisions; a shared bigint sequence would couple the modules to one database.
Microservices
What survives: each service's own indexes. What does not: a global sequence. IDs are generated in services (UUIDv7, ULID, Snowflake-style 64-bit IDs) and travel in events, so every consumer's index on order_id receives them in roughly time order if the generator is time-ordered, or randomly if not.
Order service Kafka topic orders Shipping service (PostgreSQL)
1 id = uuidv7() -> INSERT orders (right-most leaf)
2 outbox -> OrderCreated{id}
3 INSERT shipments(order_id, ...) -- index on order_id
4 v7 ids arrive ~ in time order -> near-right-most inserts
with v4 ids step 4 hits random leaves of shipments_order_id_idx on every eventConsumers that upsert by event ID for idempotency (INSERT ... ON CONFLICT (event_id) DO NOTHING) maintain a unique B-tree on that ID; with random event IDs that index becomes the write bottleneck. See Idempotent Consumers & the Inbox Pattern.
Distributed data: replicas, caches, sharded and distributed SQL
Replicas: physical replicas (PostgreSQL streaming, InnoDB with the same data) replay the same page changes, so index bloat and split-heavy WAL on the primary become replication lag; full-page images after checkpoints multiply with random keys. A REINDEX CONCURRENTLY on the primary is replayed as a full index build on every replica (Replication & Failover).
Caches: a cache in front of the database removes point lookups but not writes; every write still maintains every index.
Sharding: each shard has its own B-trees; a shard key that is also the leading index column keeps per-shard indexes small. A monotonic shard key with range sharding sends all inserts to the last shard (the distributed version of the right-most page); hash sharding spreads them but makes cross-shard ranges scatter-gather (Partitioning & Sharding).
Distributed SQL: CockroachDB and TiDB store rows in an LSM (Pebble, RocksDB/TiKV) and split the key space into ranges/regions; a monotonic primary key creates a hot range. CockroachDB's answer is hash-sharded indexes: "Hash-sharded indexes distribute sequential traffic uniformly across ranges, eliminating single-range hotspots". Spanner warns that "a monotonic key directs all insert traffic to a single server". That is the opposite of the single-node B-tree advice. Know which layer you are optimising.
Scaling path: 1×, 10×, 100×
| Load | What changes | B-tree consequence |
|---|---|---|
| 1× (one primary, indexes fit in RAM) | Defaults, bigint keys, a few indexes | 3–4 levels, all internal pages cached, splits invisible |
| 10× (tables of 100 M–1 B rows) | Indexes exceed RAM; random keys hurt; bloat visible | Monotonic keys, INCLUDE for index-only scans, drop unused indexes, scheduled pgstatindex + REINDEX CONCURRENTLY, time partitioning so old partitions' indexes go cold |
| 100× (shards, regions, services) | Distributed IDs, many writers | Time-ordered IDs (UUIDv7/ULID) for B-tree engines; spread keys for range-partitioned distributed SQL; consider LSM/columnar stores for append-only firehoses |
Lab
All experiments run against PostgreSQL 18 (needed for uuidv7()). Expected outputs are approximate: they are computed from the page arithmetic on this page and the Go model, not copied from a run; your numbers will differ by a few percent.
Setup.
docker run -d --name pg -e POSTGRES_PASSWORD=pg -p 5432:5432 postgres:18
docker exec -it pg psql -U postgresCREATE EXTENSION IF NOT EXISTS pgstattuple;
CREATE EXTENSION IF NOT EXISTS pageinspect;
-- The PK index exists BEFORE the inserts, so the insert pattern shapes the tree
CREATE TABLE t_seq (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, v int);
CREATE TABLE t_v4 (id uuid PRIMARY KEY DEFAULT uuidv4(), v int);
CREATE TABLE t_v7 (id uuid PRIMARY KEY DEFAULT uuidv7(), v int);
INSERT INTO t_seq (v) SELECT g FROM generate_series(1, 1000000) g;
INSERT INTO t_v4 (v) SELECT g FROM generate_series(1, 1000000) g;
INSERT INTO t_v7 (v) SELECT g FROM generate_series(1, 1000000) g;
VACUUM ANALYZE t_seq, t_v4, t_v7;Experiment 1: sequential vs random keys (index size, density, splits). pgstatindex has no split counter; leaf count and density show the result of the splits.
SELECT 't_seq' AS t, * FROM pgstatindex('t_seq_pkey')
UNION ALL SELECT 't_v7', * FROM pgstatindex('t_v7_pkey')
UNION ALL SELECT 't_v4', * FROM pgstatindex('t_v4_pkey');1 t | tree_level | index_size | leaf_pages | avg_leaf_density | leaf_fragmentation
2 t_seq | 2 | ~22 MB | ~2,730 | ~90 | ~0
3 t_v7 | 2 | ~31 MB | ~3,820 | ~90 | ~0
4 t_v4 | 2 | ~39-41 MB | ~4,900 | ~68-72 | ~45-50
5 v7 vs v4: same 16-byte key, ~25% fewer pages -> the difference is the split pattern
6 bigint vs v7: same append pattern, ~30% smaller -> the difference is key widthExperiment 2: REINDEX restores density.
REINDEX INDEX CONCURRENTLY t_v4_pkey;
SELECT index_size, leaf_pages, avg_leaf_density, leaf_fragmentation FROM pgstatindex('t_v4_pkey');
-- ~31 MB | ~3,820 | ~90 | ~0 (a sorted build packs leaves to fillfactor 90)Experiment 3: measure the height and look at the metapage.
SELECT root, level, fastroot, fastlevel, allequalimage FROM bt_metap('t_seq_pkey');
-- level = 2 -> 3 levels: root, one internal level, leaves
SELECT blkno, type, live_items, free_size, btpo_prev, btpo_next, btpo_level
FROM bt_page_stats('t_seq_pkey', 1);
-- type 'l' (leaf), live_items ~367, btpo_prev = 0 (left-most), btpo_next = next leaf blockExperiment 4: read a leaf with bt_page_items, then a posting list.
SELECT itemoffset, ctid, itemlen, data, htid FROM bt_page_items('t_seq_pkey', 1) LIMIT 4;
-- 1 | (2,1) | 16 | 6f 01 00 00 00 00 00 00 | <- high key (367 = 0x16f): upper bound of this leaf
-- 2 | (0,1) | 16 | 01 00 00 00 00 00 00 00 | (0,1) <- key 1 points to heap block 0, item 1
-- 3 | (0,2) | 16 | 02 00 00 00 00 00 00 00 | (0,2)
CREATE INDEX t_seq_v10_idx ON t_seq ((v % 10)); -- 10 distinct values, 1 M rows
SELECT itemoffset, itemlen, htid, cardinality(tids) AS n_tids FROM bt_page_items('t_seq_v10_idx', 1) LIMIT 3;
-- posting list tuples: itemlen in the hundreds or thousands of bytes, n_tids ~100-1,300 per tuple
SELECT pg_size_pretty(pg_relation_size('t_seq_v10_idx'));
-- a few MB; recreate WITH (deduplicate_items = off) and compare: roughly 3x largerExperiment 5: EXPLAIN a range scan along the leaves.
EXPLAIN (ANALYZE, BUFFERS) SELECT id FROM t_seq WHERE id BETWEEN 100000 AND 110000;
-- Index Only Scan using t_seq_pkey on t_seq (rows=10001)
-- Index Cond: ((id >= 100000) AND (id <= 110000))
-- Heap Fetches: 0
-- Buffers: shared hit=~30 <- 2 internal pages + ~28 leaves (10,001 / 366)
EXPLAIN (ANALYZE, BUFFERS) SELECT id FROM t_seq WHERE id BETWEEN 100000 AND 110000 ORDER BY id DESC;
-- Index Only Scan Backward ... <- the same leaves, walked through left-linksExperiment 6 (MySQL 8.4): page splits in InnoDB.
SET GLOBAL innodb_monitor_enable = 'index_page_splits';
CREATE TABLE s_v4 (id BINARY(16) PRIMARY KEY, pad CHAR(100)) ENGINE=InnoDB;
CREATE TABLE s_seq (id BIGINT AUTO_INCREMENT PRIMARY KEY, pad CHAR(100)) ENGINE=InnoDB;
-- insert 200,000 rows into each (UUID_TO_BIN(UUID()) for s_v4 is v1, time-low first: random-ish order)
SELECT name, count FROM information_schema.INNODB_METRICS WHERE name = 'index_page_splits';
-- s_v4 inserts cause several times more splits than s_seq; compare
SELECT index_name, stat_name, stat_value FROM mysql.innodb_index_stats
WHERE table_name IN ('s_v4','s_seq') AND stat_name IN ('size','n_leaf_pages');Common misconceptions
| Belief | Reality |
|---|---|
| “PostgreSQL and MySQL use B-trees, not B+trees.” | The manuals say B-tree; the structure is a B+tree (entries only in leaves, linked leaves). SQL Server says "B+ trees" outright. |
| “B-tree lookups are O(log n), so big tables get slow.” | Base ~400: 4 levels hold billions of bigint keys; the upper levels are cached. |
| “A classic B-tree is faster because it can stop early.” | Over 99% of entries are in leaves; fatter internal nodes lower fan-out for everyone. |
| “UUIDs only cost extra bytes.” | Random UUIDv4 also cause 50/50 splits, ~69% leaf fill and random dirty pages; UUIDv7 avoids most of it. |
| “fillfactor 100 is optimal.” | Only for static data; otherwise the next writes cause "a sudden flood of page splits". |
| “VACUUM shrinks indexes.” | It recycles empty pages only; half-empty pages remain until REINDEX. |
| “Deleting rows makes the index smaller.” | PostgreSQL never merges half-empty pages; InnoDB merges below MERGE_THRESHOLD but the file does not shrink. |
| “InnoDB prefix-compresses index keys.” | No: that is MyISAM PACK_KEYS and WiredTiger; InnoDB has column-prefix indexes and page compression. |
| “Low-cardinality indexes are huge.” | PostgreSQL 13+ deduplication stores each value once with a posting list. |
| “The PostgreSQL PK index is the table.” | Tables are heaps; every index, PK included, points to TIDs. InnoDB is the clustered one. |
| “Index reads lock rows.” | Tree pages are protected by microsecond latches; row locks are a transactional layer above. |
| “Hash indexes beat B-trees for equality.” | Only in size for long keys; no ranges, no ordering, no uniqueness. |
| “A wide PK only affects the PK index.” | In InnoDB every secondary index entry repeats it. |
| “Monotonic keys are always best.” | On one B-tree yes; on range-partitioned distributed SQL (CockroachDB, Spanner) they create a hot range. |
Cheat sheet
| Topic | What to remember |
|---|---|
| B-tree vs B+tree | B-tree: entries in every node, no links. B+tree: separators above, all entries in linked leaves. Engines ship B+trees. |
| Fan-out | ~400 per 8 kB page for bigint, ~290 for uuid; 16 kB InnoDB pages roughly double it |
| Height | 3 levels ≈ tens of millions, 4 levels ≈ billions of narrow keys |
| Point lookup | h page accesses (+1 heap page in PostgreSQL); usually 1–2 physical reads |
| Range scan | One descent + one page per leaf covered; both directions |
| Page split | New right page, separator copied up; cascades; root split adds a level |
| Right-most inserts | Monotonic keys fill pages to fillfactor (PG 90%) / ~15/16 (InnoDB) |
| Random inserts | ~69% average fill (ln 2), high leaf_fragmentation, more WAL |
| fillfactor | PG index default 90; lower for random inserts; 100 only for static data |
| Merge | PG deletes only empty pages; InnoDB merges below MERGE_THRESHOLD 50 |
| Concurrency | PG = Lehman–Yao B-link (high key + right-link); latches, not locks |
| PostgreSQL extras | Suffix truncation (12), deduplication (13), bottom-up deletion (14), skip scan (18) |
| Storage cost | PG: key + 6-byte TID; InnoDB secondary: key + full PK |
| Health check | pgstatindex: avg_leaf_density, leaf_fragmentation, tree_level; bt_metap, bt_page_items |
| Rebuild | REINDEX INDEX CONCURRENTLY; pg_repack; MySQL OPTIMIZE TABLE |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Why does a B+tree with 8 kB pages need only 4 levels for a billion bigint keys, while a balanced binary search tree needs about 30? Must-know
Answer
Answer: Each B+tree page holds ~366–407 entries, so each level multiplies capacity by ~400: 2.7 M leaves → 6,695 → 17 → 1 root. A BST multiplies by 2 per level: log2(10^9) ≈ 30, and each level is a separate page read on disk.
2 — Name two structural differences between a B-tree and a B+tree and one practical consequence of each. Must-know
Answer
Answer: (1) In a B+tree all entries live in leaves and internal nodes hold only separators: internal nodes are smaller, fan-out is higher, the tree is shallower. (2) B+tree leaves are linked: a range scan descends once and walks the chain instead of traversing up and down.
3 — What happens, step by step, when a leaf page in PostgreSQL is full and a new key must go into it? Important
Answer
Answer: First simple deletion of LP_DEAD items and, if applicable, bottom-up deletion, then deduplication are tried. If still no room: a new right page is allocated, part of the items move there, the right-link and high key are set, and a separator/downlink is inserted in the parent, which may split in turn; a root split adds a level.
4 — Why do UUIDv4 primary keys produce a larger index than UUIDv7 keys of the same width? Important
Answer
Answer: UUIDv4 inserts land on random leaves, which split 50/50 and average ~69% full; UUIDv7 inserts append at the right-most leaf, which PostgreSQL fills to fillfactor 90 before splitting. Same key size, different fill.
5 — What does avg_leaf_density = 45 with leaf_fragmentation = 50 in pgstatindex tell you, and what do you do? Good to know
Answer
Answer: Leaves are less than half full and their physical order is far from their logical order: the index is bloated (random inserts, mass deletes). Rebuild it with REINDEX INDEX CONCURRENTLY and consider the key choice or a lower fillfactor.
6 — In InnoDB, why does the primary key's size affect every secondary index? Important
Answer
Answer: Each secondary index record "contains the primary key columns for the row"; the PK is the row pointer. A 36-byte PK makes every secondary entry ~28 bytes larger than an 8-byte one.
7 — What problem do Lehman and Yao's high key and right-link solve? Good to know
Answer
Answer: A reader descending the tree may reach a page that was split after it read the parent. If the search key is above the page's high key, it follows the right-link to the new sibling, so readers need no locks on the path and only one page latch at a time.
8 — What changed in PostgreSQL 13 and 14 for B-tree indexes, and who benefits? Good to know
Answer
Answer: 13: deduplication (posting lists) for duplicate keys, shrinking low-cardinality and foreign-key indexes. 14: bottom-up index deletion removes version-churn entries before a split, keeping update-heavy indexes from growing.
9 — When is a full table scan the right plan? Must-know
Answer
Answer: When the query returns a large fraction of the table or the table is small: sequential I/O over all pages is cheaper than many random index + heap reads.
10 — Why is fillfactor = 100 risky on a table that receives inserts in the middle of the key range? Important
Answer
Answer: Every page is full, so the first insert into any page splits it; a burst of inserts becomes a flood of splits, half-empty pages and WAL.
11 — Why might CockroachDB advise against monotonically increasing primary keys when PostgreSQL advises for them? Good to know
Answer
Answer: CockroachDB range-partitions the key space across nodes; monotonic keys send all inserts to the last range (one hot node). PostgreSQL has a single B-tree, where monotonic keys give dense, append-only pages.
Glossary
| Term | Meaning |
|---|---|
| B-tree | Bayer & McCreight's balanced multiway tree; nodes are pages; entries in every node |
| B+tree | Variant with all entries in leaves, separators above, leaves linked (Comer's name for Knuth's variant) |
| B*-tree | Knuth's variant that redistributes before splitting to keep nodes ≥ 2/3 full |
| B-link tree | Lehman & Yao's B+tree with a high key and right-link on every node, for concurrency |
| Prefix B-tree | Bayer & Unterauer 1977: shortened separators; ancestor of suffix truncation |
| Binary search tree | One key, two children per node; height ~log2(n), too tall for disk |
| Order | Capacity parameter of a B-tree: Bayer's k (min keys) or Knuth's m (max children) |
| Fan-out | Number of children per internal page |
| Height | Number of levels from root to leaf; tree_level + 1 in pgstatindex |
| Node = page | Each tree node is one database page (8 kB PostgreSQL, 16 kB InnoDB) |
| Root / internal / leaf page | Top page / navigation pages / pages holding the entries |
| Separator | Key in an internal page that divides two subtrees |
| Pivot tuple | PostgreSQL's name for a separator + downlink tuple (and high keys) |
| Downlink | Pointer from an internal tuple to a child page |
| High key | Upper bound of keys allowed on a page (item 1 on non-right-most PostgreSQL pages) |
| Right-link / left-link | Sibling pointers on the same level (btpo_next / btpo_prev) |
| Sequence set | Comer's term for the linked list of leaves |
| Metapage | Block 0 of a PostgreSQL B-tree: root location and level (bt_metap) |
| Full table scan | Reading every page of a table (Seq Scan, type: ALL) |
| Point lookup | Equality search: one root-to-leaf descent |
| Range scan | One descent, then walking leaves via sibling links |
| Sequential I/O | Reading adjacent pages; cheap per page |
| Random I/O | Reading scattered pages; one seek or request per page |
seq_page_cost / random_page_cost | PostgreSQL planner costs for sequential vs random page reads (1 / 4) |
| Page split | Moving part of a full page to a new page and adding a downlink in the parent |
| Root split | Split of the root: tree grows one level |
| Right-most split | Split that keeps the left page full when inserting the largest key |
| Merge / underflow | Combining an under-full page with a neighbour (InnoDB MERGE_THRESHOLD) |
MERGE_THRESHOLD | InnoDB page-fill percentage (default 50) below which it tries to merge |
| Fill factor / fillfactor | Target page fill at build time (PostgreSQL 90 for B-tree) |
innodb_fill_factor | InnoDB fill for sorted index builds (default 100, 1/16 kept free) |
| Sorted index build | InnoDB's bottom-up bulk load when creating/rebuilding an index |
innodb_page_size | InnoDB page size (default 16 KB), fixed at initialisation |
| Monotonic key | A key that only increases (identity, timestamp, UUIDv7) |
| UUIDv4 / UUIDv7 | Random UUID / UUID whose first 48 bits are a millisecond timestamp |
| ULID | 128-bit time-ordered ID with a 26-character text form |
| Fastpath (right-most cache) | PostgreSQL's cached right-most leaf for increasing keys |
| Latch | Short in-memory lock on a page/buffer, not transactional |
| Latch coupling (lock coupling, crabbing) | Hold the parent latch until the child is latched |
| Deduplication | PostgreSQL 13+: store a duplicate key once with many TIDs |
| Posting list | Sorted TID array attached to one key value |
deduplicate_items | PostgreSQL index option enabling deduplication (default on) |
| Bottom-up deletion | PostgreSQL 14+: delete version-churn entries before a leaf split |
| Version churn | Extra index entries created by non-HOT updates |
LP_DEAD | Line-pointer flag marking an index entry known dead; enables simple deletion |
| HOT | Heap-only tuple update: no new index entries (PostgreSQL) |
| Suffix truncation | PostgreSQL 12+: drop trailing columns from pivot tuples |
| Prefix compression | Storing a shared key prefix once (MyISAM PACK_KEYS, WiredTiger) |
PACK_KEYS | MyISAM option for key prefix compression |
ROW_FORMAT=COMPRESSED | InnoDB zlib page compression with a modification log |
| TID / ctid | PostgreSQL physical row address (block, item); 6 bytes |
| Heap table | Unordered table storage pointed to by indexes (PostgreSQL, Oracle default, SQL Server heap) |
| Clustered index | Table stored as the PK B+tree (InnoDB, SQL Server clustered, Oracle IOT) |
GEN_CLUST_INDEX | InnoDB's hidden clustered index on a 6-byte row ID when no PK exists |
| Secondary index | Any non-clustered index; in InnoDB it stores the PK |
| Index-only scan | Answer from the index without visiting the heap (needs visibility map) |
Covering index / INCLUDE | Index carrying extra payload columns to enable index-only scans |
| Visibility map | PostgreSQL bitmap of all-visible heap pages, used by index-only scans |
| Skip scan | PostgreSQL 18+: use a multicolumn index without an equality on its first column |
WITHOUT ROWID | SQLite table clustered on its primary key |
| Index size estimation | Entries × (tuple + line pointer) ÷ (usable page × fill) |
| Index bloat | Index size well above its ideal due to sparse pages |
avg_leaf_density | pgstatindex: average leaf fill percentage |
leaf_fragmentation | pgstatindex: percentage of leaves whose next leaf is physically earlier |
pgstatindex | pgstattuple function reporting B-tree level, size, density, fragmentation |
pageinspect | Extension to read raw pages (bt_metap, bt_page_stats, bt_page_items) |
bt_page_items | Lists tuples of one B-tree page, including htid and tids |
REINDEX / REINDEX CONCURRENTLY | Rebuild an index (online variant PostgreSQL 12+) |
pg_repack | Extension/tool that rebuilds tables and indexes online |
OPTIMIZE TABLE | MySQL: rebuild an InnoDB table and its indexes |
Buffer pool / shared_buffers | Engine page cache (InnoDB / PostgreSQL) |
| Write amplification | Bytes written to storage per byte of logical change |
| LSM-tree | Log-structured merge tree: memtable + sorted immutable files + compaction |
| Hash index | Equality-only index on a hash of the key |
amcheck | PostgreSQL extension that verifies B-tree invariants (bt_index_check) |
References
- R. Bayer and E. McCreight, Organization and Maintenance of Large Ordered Indices, Boeing Scientific Research Laboratories, Mathematical and Information Sciences Report No. 20, July 1970 (journal version: Acta Informatica 1, 173–189, 1972, doi:10.1007/BF00288683). Report PDF (archived USC copy)
- D. Comer, The Ubiquitous B-Tree, ACM Computing Surveys 11(2), 1979. PDF
- P. Lehman and S. B. Yao, Efficient Locking for Concurrent Operations on B-Trees, ACM TODS 6(4), 1981. PDF
- G. Graefe, A Survey of B-Tree Locking Techniques, ACM TODS 35(3), 2010. PDF. (Modern B-Tree Techniques, Foundations and Trends in Databases 3(4), 2011, was not accessible.)
- PostgreSQL source: src/backend/access/nbtree/README
- PostgreSQL documentation: B-Tree Indexes (incl. Implementation, Bottom-up Index Deletion, Deduplication), CREATE INDEX, REINDEX, pgstattuple, pageinspect, Index-Only Scans, Database Page Layout, Hash Indexes, UUID functions; release notes 12, 13, 14, 18
- MySQL 8.4 Reference Manual: Clustered and Secondary Indexes, The Physical Structure of an InnoDB Index, Sorted Index Builds, Configuring the Merge Threshold for Index Pages, InnoDB Limits, How Compression Works for InnoDB Tables, CREATE TABLE (PACK_KEYS)
- SQLite: Database File Format, B-tree Pages
- Microsoft: SQL Server index architecture and design guide
- MongoDB: WiredTiger Storage Engine
- CockroachDB: Storage Layer
- Laravel 13: Eloquent: UUID and ULID Keys, Migrations, Strings (Str::uuid7), Artisan Console; framework source HasUuids.php
- Go:
sort,math/rand/v2,github.com/google/btree,go.etcd.io/bbolt