SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
  • Common Database Types
  • SQL vs NoSQL
  • ACID Transactions
  • B-Trees and B+ Trees
  • LSM Trees
  • Transaction Isolation Levels
  • Locking and MVCC
  • Normalization
  • OLTP vs OLAP
  • BASE and PACELC
  • Write-Ahead Log (WAL)
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Data and Storage/Database Basics

B-Trees and B+ Trees

The tree that lets a database find one row among millions in a few steps.

⏱ 15 min readAdvancedInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

A B-tree is a sorted, balanced tree built from disk-sized nodes. It lets a database find one row among millions by reading only 3 or 4 pages. A B+ tree is the popular version, where all the data lives in the bottom level.

  • Each node is a page (a block of disk, often 4 to 16 KB) holding hundreds of keys, so the tree is very wide and very short.
  • Searching, inserting and deleting all take O(log n) page reads.
  • The B+ tree links its leaves in a row, so range queries (ages 20 to 30) are fast.
  • It is the default index in PostgreSQL, MySQL (InnoDB), SQL Server and Oracle.

02Concept: What is it?

Reading from disk is slow, and it is done in pages, not single bytes. A plain binary tree has only 2 children per node, so a million keys need about 20 levels, which means 20 disk reads. A B-tree gives each node hundreds of children, so the same million keys need only 2 or 3 levels.

A small B+ tree
🌳Root[ 20 | 40 ]
[5 | 10]keys < 20
[25 | 30]20 to 39
[45 | 50]40 and up
πŸƒ1 3 5
→↓next
πŸƒ10 15
→↓next
πŸƒ20 25 30
→↓next
πŸƒ40 45 50
Guide nodes (root and inner) Leaves: the real keys, linked in order
Inner nodes only guide the search (like road signs). The leaves hold the keys, and are linked so you can walk across them in order.
🧠B-tree vs B+ tree
In a classic B-tree, every node can hold keys and their data. In a B+ tree, inner nodes hold only keys for guiding, and all data is in the leaves. Inner nodes are smaller, so more fit in memory, and the linked leaves make range scans easy. Almost every database uses the B+ variant, and people often just say β€œB-tree” for it.

03Real-Life Example

🍡The Library Aisle Signs
You need one book in a huge library. At the door a sign says: β€œFiction left, Science right.” You go right. The next sign says: β€œA to M, N to Z.” Then a shelf label says which exact shelf. After 3 signs you are at the right shelf, even though the library has a million books. The signs are the inner nodes. The shelf is a leaf. And the books on a shelf are already sorted, so reading β€œall books from Mars to Mercury” is just walking along the shelf.
Library
B+ tree
Entrance sign
Root node
Smaller signs deeper in
Inner nodes
The shelf
Leaf node (a page on disk)
Books on the shelf, sorted
Keys (and row pointers) inside a leaf
Walking along to the next shelf
Linked leaves for range scans
A full shelf, so you split it in two
Node split
Finding key 45
🌳Root45 is above 40, go right
→↓read 1
Inner nodebetween 45 and 50
→↓read 2
πŸƒLeaf 40 45 50found 45
Three page reads, no matter how many rows the table has (well, about 3 or 4).

04Why Do We Need It?

πŸ’½Disks read in pages
One page read costs about the same whether it holds 1 key or 500. So pack each page full of keys.
πŸ”Fast lookups
Finding one row among a billion needs only about 4 page reads.
πŸ“Ordered data
Keys stay sorted, so ranges, sorting and min or max are cheap.
βš–οΈAlways balanced
Every leaf is at the same depth, so every lookup costs about the same.
✍️Updates in place
Inserts and deletes change a few pages, and keep the tree in shape by splitting and merging.
πŸ—£οΈInterview basics
β€œHow does an index work?” almost always ends at a B+ tree.
B-trees are built around one fact: reading a disk page is the expensive part, so make each read count.

05Where Do We Use It?

🐘PostgreSQL
The default index type is a B-tree (a B+ style structure).
🐬MySQL InnoDB
The table itself is stored as a B+ tree ordered by primary key.
πŸͺŸSQL Server and Oracle
Their standard indexes are B+ trees.
πŸƒMongoDB (WiredTiger)
Indexes are B-tree based.
πŸ—‚οΈFile systems
NTFS, ext4 (HTree), APFS and Btrfs use B-tree style structures for directories and metadata.
πŸ—ƒοΈSQLite and embedded stores
SQLite, LMDB and BoltDB are built around B-trees.

06Types / Parts / How It Works

How a B+ tree works

OperationWhat happensCost
SearchStart at the root. At each node, pick the child whose range holds the key. Stop at a leaf.One page read per level, about 3 to 4
InsertFind the right leaf and add the key in order. If the leaf is full, split it in two and push a separator key up to the parent.Search cost, plus a split now and then
Node splitA full node becomes two half-full nodes. If the parent is full too, it splits as well. A root split makes the tree one level taller.Rare, and the tree grows from the top, so it stays balanced
DeleteRemove from the leaf. If it gets too empty, borrow from a neighbour or merge with it.Search cost, plus a merge now and then
Range scanSearch for the start key, then follow the leaf links until the end key.One search, then sequential reads
A leaf splits
Before
Parent [ 40 ]
πŸƒ[ 20 | 25 | 30 ] full
→↓insert 22
After
Parent [ 25 | 40 ]
πŸƒ[ 20 | 22 ]
→↓next
πŸƒ[ 25 | 30 ]
Inserting 22 into a full leaf. The leaf becomes two. The first key of the new leaf is copied into the parent as a signpost.
B-tree
Data in every node
  • A key can be found before reaching a leaf
  • Each key appears once in the tree
  • Range scans need to climb up and down
  • Nodes are bigger, so fewer keys fit per page
B+ tree
Data only in leaves
  • Every search goes to a leaf, so cost is steady
  • Some keys are repeated as signposts
  • Leaves are linked, so range scans are fast
  • Inner nodes are small, so very wide and shallow
πŸ“Clustered vs secondary index
In MySQL InnoDB the leaves of the primary key tree hold the whole row (a clustered index). A secondary index leaf holds the primary key, so a lookup does a second tree walk. PostgreSQL stores rows in a separate heap, and every index points to the row location.
VisualizerGrow a B+ tree and search itPress Insert and watch nodes split. Move the search slider to see which pages are read. Then scale up the row count to see why real trees stay short.
Max keys per node (the order)
B+ tree after 12 inserts. Top row is the root. Bottom row is the leaves, which hold the keys and are linked left to right. Amber border = pages read by the search.
root
58
inner
2138
75
leaves
1411
2131
3848
5868
758595
Tree height
3
levels
Splits so far
5
Pages read: tree
3
key found
Pages read: full scan
5
read every leaf
The last insert (key 4) found room in a leaf, so nothing split. Keep inserting until a node overflows.
Now scale it up: why real trees stay shallow

Real nodes are whole disk pages (often 4 to 16 KB) holding hundreds of keys, so each level multiplies by a large number.

Tree height
3
page reads per lookup
Full scan
5,000
page reads

With 200 keys per page, even 10^9 rows need only about 4 levels. In practice the upper levels stay in memory, so a lookup may hit the disk once or twice.

A teaching model: keys come from a fixed, repeatable order (no random numbers), leaves split in the middle and the separator key is copied up, and a node is counted as one page read. Real engines also handle deletes, merges, variable-size keys and concurrency.

07How to Use It / Steps / Implementation

Using B-tree indexes well

  1. 1
    Index the columns you filter, join and sort on
    A B+ tree index helps WHERE, JOIN, ORDER BY and range conditions such as dates between two values.
  2. 2
    Choose composite index order carefully
    An index on (country, city) helps queries on country, or on country and city. It does not help a query on city alone.
  3. 3
    Prefer small, steady keys
    Narrow keys fit more per page, so the tree is shorter. Random wide keys (like random UUIDs) scatter inserts across pages and cause more splits.
  4. 4
    Insert in order when you can
    Increasing keys (auto numbers, time-ordered ids) append to the right-most leaf, which is cheap.
  5. 5
    Leave room with a fill factor
    A fill factor below 100 percent leaves free space in pages, so fewer splits happen on update-heavy tables.
  6. 6
    Remember every index costs writes
    Each insert or update must change every index on the table. Add only those you need.
  7. 7
    Check with EXPLAIN
    Ask the database for its plan. Look for an index scan, not a full table scan, on large tables.
⚠️Write-heavy workloads
B-trees update pages in place, which means random writes on disk. For very high write rates, LSM trees (next topic) are often a better fit.

08Key Terms to Know

TermMeaning in easy words
Page / blockThe unit of disk read and write, often 4 to 16 KB
NodeOne page of the tree: a root, an inner node or a leaf
LeafA bottom node that holds the real keys (and values or row pointers)
Fan-out / branching factorHow many children a node has. Bigger means a shorter tree
HeightThe number of levels from root to leaf, which is the cost of a lookup
SplitDividing a full node in two and sending a separator key to the parent
MergeJoining two nearly empty neighbours into one
Range scanReading all keys between a low and a high value
Clustered indexAn index whose leaves hold the full rows, so the table is stored in key order
Fill factorHow full a page is left when built, to leave room for inserts

09Pros, Cons and Trade-offs

βœ… Pros
  • Fast reads: a few page reads per lookup
  • Great for range queries and sorting
  • Predictable, balanced performance
  • Mature and well understood
  • Works well for mixed read and write loads
⚠️ Cons
  • Updates in place cause random disk writes
  • Splits and merges add work and can fragment pages
  • Writes also go to a log (WAL) first, so data is written twice
  • Random keys cause many splits
  • Pages are often only partly full, so space is wasted

Trade-offs

ChoiceWe gainWe lose
Bigger pagesShorter tree, fewer readsMore data read and written per change
Higher fill factorLess space, faster scansMore splits on insert
More indexesFaster reads on more columnsSlower writes, more disk
Wider keysSimpler to use (for example a text key)Lower fan-out, taller tree
B+ tree (vs hash index)Range queries and orderingSlightly slower for pure equality lookups

10Common Problems and Mistakes

Common mistakes

  1. Random UUID primary keys on a clustered index. Every insert lands in a random leaf, causing splits and a cold cache. Time-ordered ids behave much better.
  2. Too many indexes. Each write updates all of them. Read speed rises and write speed falls.
  3. Wrong column order in a composite index. The leftmost column must be used by the query.
  4. Functions on indexed columns. WHERE LOWER(name) = 'x' cannot use a plain index on name.
  5. Indexing low-variety columns. A yes or no column splits the table into two big halves, so the index barely helps.
  6. Never rebuilding bloated indexes. After many deletes and updates, pages can be half empty.

Things to watch

🧩Fragmentation
Leaves end up out of order on disk, so scans turn into random reads.
πŸ”’Concurrency
Many writers touch the same pages. Engines use latches and clever protocols to keep the tree safe.
πŸ“ˆWrite amplification
Changing one small row rewrites a whole page, plus a log record.
🧠Cache fit
Fast only if the upper levels stay in memory. A huge index that does not fit slows down.

11Real-World Examples

🐘PostgreSQL
CREATE INDEX makes a B-tree by default. Other types (hash, GIN, GiST, BRIN) are chosen for special jobs.
🐬MySQL InnoDB
Stores each table as a clustered B+ tree on the primary key, with secondary B+ tree indexes beside it.
πŸ—‚οΈFile systems
Btrfs, XFS, NTFS and APFS use B-tree style structures to find files and extents (general idea).
πŸͺΆSQLite
Every table and index is a B-tree stored in one file.
πŸ”‘LMDB, BoltDB
Embedded key-value stores built on copy-on-write B+ trees.
πŸƒMongoDB
Indexes are B-tree based, with the WiredTiger engine.
πŸ“Note
These are general ideas. Each engine tunes its tree (page size, latching, compression), so details differ.
Why a billion rows is still about 4 reads
Level 11 root page
→↓x 200
Level 2200 pages
→↓x 200
Level 340,000 pages
→↓x 200
πŸƒLevel 48 million leaf pages, over a billion keys
With around 200 keys per page, each level multiplies the reach by 200.

12Related Topics to Read Next

Indexing→

B+ trees are what most indexes are made of.

LSM Trees→

The write-optimised alternative.

Relational Databases→

Where B+ tree indexes are the default.

Query Optimization→

Using EXPLAIN to see whether an index is used.

ACID Transactions→

The write-ahead log that protects B-tree updates.

Partitioning→

Smaller trees from splitting a big table.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • βœ”What: a sorted, balanced tree whose nodes are disk pages with many keys.
  • βœ”Cost: O(log n), but about 3 to 4 page reads for billions of rows.
  • βœ”B+ tree: data only in leaves, leaves linked, so range scans are quick.
  • βœ”Insert: add to a leaf. If full, split and push a key up. The tree grows from the root.
  • βœ”Delete: remove, then borrow from or merge with a neighbour.
  • βœ”Good keys: small and ordered. Random wide keys cause splits.
  • βœ”Weak spot: random in-place writes. For heavy writes, think LSM.
  • βœ”One line: β€œA wide, short, sorted tree that turns a billion rows into four page reads.”
← Previous
ACID Transactions
Next β†’
LSM Trees