MediumLow-Level DesignMicrosoftAsked in 202310 min read
Explain database indexing and B-trees
533 views
34 of 106
1
The problem
Question presented to candidate:
"A query on a 50-million-row table takes seconds, and adding an index makes it take a millisecond. Explain what an index actually is, why databases use B-trees for it, and what a lookup and a range query do inside the tree. What does the index cost you?"
What a strong answer should cover:
An index is a separate sorted structure mapping column values to row locations, so the database avoids a full table scan
Why a B+tree: nodes are disk pages with high fan-out, so the tree is only 3-4 levels deep even for a billion keys; lookups cost O(log n) page reads, and the top levels sit in memory
Keys live in sorted, linked leaves, so one tree serves equality, ranges, ORDER BY and prefix matches โ a hash index serves only equality
Inserts keep the tree balanced by page splits; sequential keys and random keys fill pages differently
The cost: every insert, update of an indexed column and delete must maintain every index (write amplification), plus storage; clustered (InnoDB primary key) vs secondary indexes
Contrast with LSM trees (RocksDB, Cassandra) as the write-optimised alternative
Code / implementation expected: Optional โ explaining the tree is enough; the example builds a B+tree and counts the pages each operation reads.
databases
indexing
2
Try it yourself
Sketch your approach before you read the solution. That is what the interview tests.
Stuck? Get a hint.
A short nudge toward the approach. It will not give the answer away.
3
Solution
Target Audience: Beginners to databases โ you know what a table and a row are; no data-structures background needed beyond "sorted lists are easy to search".
Difficulty: Medium
Verified with: Node 22.22, Python 3.12, Go 1.24 and Java 21 (all four print identical output).
How to read this doc: Every idea is explained in plain language first, then tagged with ๐ Interview term: so you also learn the exact words an interviewer expects. Behaviour shown comes from running the example; the Verified section quotes the full output.
This page is about what an index is and how the B-tree works inside. For which indexes to create for real queries โ composite column order, covering and partial indexes, selectivity โ see the companion page What indexing strategies improve database performance?.
The solution is hidden so you can try first
10 min read ยท 11 sections
4
Read the code
A B+tree from scratch: page splits, height, point lookups and range scans