Imagine searching an online store for a past order, opening a customer profile at work, or loading a message thread with years of history. The application may feel instant, even though the underlying database contains millions—or billions—of records.
That speed does not come from scanning every row one by one. A database needs a compact map that points it toward the right data with very few storage reads.
For many database systems, that map is built with a family of data structures called B-trees. They are one of the most practical ideas in computer science: designed not just for fast searching in theory, but for the physical reality of disks, SSDs, memory pages, and changing data.
Understanding B-trees makes database indexes less mysterious. It also helps explain why some queries are fast, why others are slow, and why a seemingly simple index can make writes more expensive.
🌳 What a B-Tree Is
A B-tree is a balanced search tree that stores sorted keys in nodes. A key might be a customer ID, a date, an email address, or a combination such as (department, last_name).
Unlike a simple binary search tree, a B-tree node can hold many keys and many child pointers. This wide shape keeps the tree short, which is crucial when nodes are read from storage rather than accessed only in memory.
The name is simply “B-tree,” not “binary tree.” The exact origin of the B is less useful than remembering the central distinction: B-trees are broad, balanced trees built for external storage.
🗂️ Why Databases Need Indexes
Without an index, finding one record often requires a table scan: reading records until the database finds the requested value. For a small table, that can be acceptable. For a large table, it can require substantial work.
An index stores selected key values in sorted order along with enough location information to find the matching row. It is similar to a book index: it does not contain every sentence, but it directs you quickly to the relevant page.
B-trees are a common structure for these indexes because they support both exact lookups and ordered operations efficiently.
📚 The Library Shelf Analogy
Picture a library with books arranged alphabetically. Instead of checking every book title, you first look at shelf labels: A–C, D–F, G–J, and so on. Once you choose a shelf, you use finer labels until you reach the book.
A B-tree works in a similar way. The upper nodes contain guide keys that divide the possible search space. Lower nodes narrow the choice further, and a leaf node eventually contains the target key or its location.
The useful twist is that each “shelf label” can hold many boundaries, not just one. That is why one step can eliminate a large portion of the search space.
🧱 Nodes, Keys, and Child Pointers
A B-tree consists of nodes. Each node usually corresponds to a fixed-size unit of storage, often called a page or block. Database engines commonly choose page-sized nodes because storage devices and operating systems naturally read and cache data in pages.
A node contains sorted keys and pointers. A pointer tells the database where another node, or sometimes a record, can be found.
- Keys divide values into ranges.
- Child pointers lead to nodes covering those ranges.
- Leaf entries lead to records or contain record data, depending on the index design.
For example, an internal node containing 20 and 50 can direct a search for 34 into the child range between those two keys.
🔎 Searching from Root to Leaf
A search begins at the root, the single top node. The database compares the requested key with the keys stored there and chooses the child pointer whose range could contain the target.
It repeats this process at each lower level. Because keys inside each node are sorted, the engine can locate the appropriate pointer efficiently, often using a small search within the page.
Suppose a tree root separates IDs into ranges below 1000, 1000–4999, and 5000 or higher. Looking up ID 3721 immediately discards two broad regions before the next page is even read.
📏 Why Wide Trees Are So Short
A binary search tree has at most two children per node. A B-tree may have dozens, hundreds, or more children, depending on page size and the size of its keys and pointers.
This count is called the tree’s fan-out. Higher fan-out means each level partitions the data into many more ranges, so large collections can often be represented with only a small number of levels.
That matters because an access to a page not already in memory can be much more costly than comparisons performed within a loaded page. B-trees are designed to minimize those expensive page visits.
⚖️ The Meaning of Balanced
A B-tree remains balanced: all leaf nodes appear at the same depth. No branch becomes much longer than another because of the order in which values were inserted.
This gives predictable search behavior. A lookup for a recently added key does not take a fundamentally longer route than a lookup for an older key in another part of the key range.
Balance is maintained automatically through split, merge, and redistribution operations. These updates add work during modification, but they protect the tree from gradually becoming inefficient.
➕ Inserting a New Key
To insert a key, the database first follows the normal search path to the proper leaf node. If that leaf has room, it places the new key in sorted position and updates the associated record reference.
If the leaf is full, the database cannot simply append beyond the page boundary. It must reorganize the structure while preserving sorted order and the tree’s balancing rules.
Most inserts affect only a path from the root to one leaf. That locality is one reason B-trees can handle continual updates well.
✂️ What Happens During a Node Split
When a node is full, it is split into two nodes. Roughly half of the entries remain in the original node, while the others move to a new sibling node.
A separator key is then inserted into the parent so future searches know which child covers which range. If the parent is also full, the split can propagate upward.
In the unusual case that the root splits, a new root is created. The tree becomes one level taller, but it remains balanced.
➖ Deleting Keys Without Breaking the Tree
Deletion starts by locating the key and removing its entry. If the affected node still has enough entries, no major restructuring is needed.
If it becomes too empty, the engine may borrow an entry from a neighboring node or merge two neighboring nodes. Parent separator keys must be updated to reflect the new boundaries.
Deletion logic is more involved than insertion because the tree must avoid sparsely populated nodes that waste pages and increase its height. Database implementations may also defer some cleanup rather than immediately performing every possible merge.
📦 Pages Are the Real Unit of Work
Textbook diagrams show individual keys and arrows. Real database engines care deeply about pages: fixed-size chunks stored on disk and copied into memory buffers.
When a query needs a B-tree node, the engine typically reads the entire page containing that node. It can then examine all keys in that page cheaply compared with requesting many separate storage locations.
This is the core design insight: pack many routing decisions into one page, then make each page read count.
💾 Disk Access, SSDs, and Caching
B-trees were originally associated with hard disks, where random seeks were especially expensive. They remain useful on SSDs because reading and writing storage still has meaningful overhead compared with CPU operations and memory access.
Frequently used upper tree levels are often retained in the database buffer cache. If the root and first internal level are already cached, a lookup may need to fetch only a lower-level page and perhaps a data page.
Performance therefore depends on more than the abstract tree shape. Memory availability, workload patterns, page size, concurrency, and the storage engine all influence actual results.
🧭 Internal Nodes and Leaf Nodes
Internal nodes primarily guide the search. Their keys divide the value space and their pointers lead to child nodes.
Leaf nodes represent the final sorted level. In a traditional B-tree, both internal and leaf nodes can contain associated records. In a B+ tree, a common database variant, record references or row data are concentrated at the leaves.
This distinction affects how scans work and how much branching information can fit into upper levels.
🌿 Why Many Databases Use B+ Trees
Many systems described casually as using “B-tree indexes” use structures closer to B+ trees. In a B+ tree, internal nodes store separator keys and child pointers, while leaf nodes hold the searchable entries.
Leaf nodes are commonly linked in key order. After finding the first matching leaf entry, the database can follow the leaf links to read subsequent values without returning to the root.
The terminology varies across documentation and products, so it is sensible to check a specific database’s storage-engine details. The practical idea remains the same: a shallow, sorted, page-oriented search structure.
↔️ Range Queries Are a Major Strength
B-trees excel at questions such as “show orders placed from Monday through Friday” or “find products priced between 20 and 50.” The database seeks to the first qualifying key, then reads forward through sorted leaf entries.
That is very different from a hash index, which is excellent for direct equality lookup but does not naturally arrange keys in order.
Range access can also support conditions such as created_at >= ..., prefix-like text patterns under appropriate collation rules, and ordered pagination. The details depend on the database and query expression.
🔤 Sorted Order Enables More Than Searching
Once values are ordered, a database can often use an index to avoid a separate sorting step. A query requesting rows ordered by an indexed column may be able to read the index in order.
Ordered indexes also help with minimum and maximum values, grouped processing in some plans, and finding the next or previous record relative to a known key.
An index is therefore not merely a yes-or-no membership test. Its ordering is often as valuable as its ability to locate one exact value.
🎯 Exact Match Lookups
For a query such as WHERE customer_id = 8421, a B-tree follows one route from root to leaf. If the key is unique, the search identifies at most one matching entry.
If the key is not unique, the matching entries are typically grouped together in sorted order. The database can find the first occurrence and then read the nearby matching entries.
Exact lookup remains efficient, although a specialized hash index may be competitive for equality-only workloads. The B-tree’s broader capabilities often make it the more generally useful default.
🧩 Composite Indexes and the Leftmost Rule
A composite index uses more than one column, such as (last_name, first_name) or (account_id, created_at). Entries are sorted first by the leading column, then by the next column within each leading value.
An index on (account_id, created_at) can efficiently support an account filter and then a date range or ordering within that account. It can often support a lookup by account_id alone too.
But a query filtering only by created_at cannot usually navigate directly through that index’s main ordering. This is often called the leftmost-prefix principle, though optimizer behavior and exceptions vary by database.
🗃️ Clustered and Secondary Indexes
In some storage engines, a clustered index determines the physical or logical organization of table data. Leaf entries may contain the full rows, arranged by the clustered key.
A secondary index stores its own key plus a reference to the underlying row. That reference may be a physical location or the clustered key, depending on the engine.
This leads to an important practical consequence: using a secondary index may require a second lookup to retrieve columns that are not already present in the index.
🪟 Covering Indexes and Index-Only Reads
An index can sometimes contain every value needed by a query: filtering columns, join columns, selected columns, and possibly ordering columns. This is commonly called a covering index.
For example, an index on (account_id, created_at, status) might cover a query that selects created_at and status for one account. The engine may answer it from index pages without fetching full table rows.
That can reduce I/O, but wider indexes consume more storage and make updates heavier. A covering index is useful when it matches an important, repeated access pattern—not merely because more indexed columns sound better.
🚦 Unique Indexes and Data Integrity
A unique B-tree index does more than speed up lookups. It helps enforce a rule that no two rows may share the same key, such as an employee number or account email under the database’s comparison rules.
Before accepting an insert or update, the database checks whether an equal key already exists. If it does, the operation is rejected unless the database’s conflict-handling syntax instructs another action.
Unique indexes illustrate a broader point: indexes participate in both query performance and correctness constraints.
🧱 Why Indexes Make Writes Cost More
Every additional index is another structure the database must maintain. An insert may need to add entries to several B-trees; an update to an indexed column may need to remove and add entries; a delete must remove index entries.
Page splits, transaction logging, locking or version tracking, and cache pressure can add further work. The cost is not identical for every write, but it is real.
The right question is not “should every searchable column have an index?” It is “which indexes provide enough read-side value to justify their write-side and storage costs?”
🧨 Sequential Keys and Hot Pages
Sequential keys, such as steadily increasing numeric identifiers, often insert near the rightmost edge of a B-tree. This can reduce scattered insert locations, but under heavy concurrent writing it may concentrate activity on a small set of pages.
Random keys distribute inserts across more parts of the tree, which can reduce one kind of contention while increasing page splits and reducing locality. Neither pattern is universally superior.
The best choice depends on the database engine, workload concurrency, key format, replication design, and operational goals. Key design is a systems decision, not just a naming choice.
🧹 Fragmentation and Page Fill
As inserts and deletes occur, B-tree pages may become unevenly filled. Pages with unused space can increase the number of pages that must be read for a scan and can weaken cache efficiency.
Some engines leave deliberate free space in pages to accommodate future inserts without immediate splits. Others provide maintenance operations that rebuild or reorganize indexes when fragmentation becomes a measured problem.
Maintenance should be based on observed workload effects, not performed automatically out of habit. Rebuilding an index also consumes resources and can affect concurrent activity.
🔐 Concurrency and Transaction Safety
Databases must let many transactions search and modify indexes at once without exposing corrupted structure or inconsistent results. This requires carefully coordinated page changes.
Implementations can use locks, latches, logging, multi-version concurrency control, or combinations of these techniques. The exact mechanism is engine-specific, but the objective is consistent: a reader should not follow a pointer into a half-finished split.
Because these mechanisms are complex, performance issues under concurrent writes are not explained by tree theory alone. Transaction isolation, hardware, and application behavior matter too.
🆚 B-Trees Compared with Hash Indexes
| Feature | B-tree or B+ tree | Hash index |
|---|---|---|
| Exact equality lookup | Efficient | Often efficient |
| Range lookup | Efficient because keys are ordered | Generally unsuitable |
| Ordered results | Can support ordered traversal | Does not preserve useful key order |
| Prefix and nearest-value operations | Often supported under suitable conditions | Generally not a natural fit |
| Typical role | General-purpose database index | Specialized equality access |
Hash indexes map a key through a hash function into a bucket. They can be effective when the workload is narrowly focused on equality tests, but their lack of ordering limits them for many SQL patterns.
🌐 Other Structures Have Different Jobs
B-trees are not the answer to every search problem. Full-text search commonly uses inverted indexes, which map terms to documents or rows. Spatial data may use specialized spatial indexes, and some analytic systems use columnar layouts or bitmap-like techniques.
Log-structured merge trees, or LSM trees, are another major alternative. They can favor high write throughput by writing sequentially and merging sorted files later, while accepting different read and maintenance trade-offs.
Choosing an index structure should follow the data type and workload. “Fast lookup” is not a single requirement.
🧪 Reading a Query Plan
Database query plans reveal whether the optimizer expects to use an index and how. Terms differ by product, but plans commonly show an index seek, index scan, table scan, sort, join method, and estimated row counts.
An index seek usually means the engine can navigate to a relatively narrow key range. An index scan means it reads a broader portion of the index, which can still be appropriate when many rows are needed.
Do not assume a table scan is automatically wrong. If a query needs most of a small table, scanning may be cheaper than bouncing through an index and fetching many individual rows.
🛠️ Practical Index Design Questions
Before creating an index, start with actual queries. Identify which columns filter rows, join tables, establish ordering, or support frequent range conditions.
- How selective is the condition—does it eliminate many rows or very few?
- Does the query need rows in a particular order?
- Are multiple predicates commonly used together?
- How often is the table written compared with read?
- Could one composite index serve several high-value queries?
Then test using realistic data volume and query plans. A design that looks elegant on a tiny development dataset may behave differently once pages no longer fit comfortably in memory.
⚠️ Common B-Tree Index Mistakes
A frequent mistake is indexing every column “just in case.” This can slow writes, enlarge backups, consume memory, and give the optimizer many overlapping choices without solving a real query problem.
Another is wrapping an indexed column in a function, such as transforming a date or changing text case in the predicate. Depending on the database and available expression indexes, that may prevent a normal B-tree index from being used effectively.
Other avoidable problems include leading wildcard searches, mismatched data types, poorly ordered composite keys, and using an index for a condition that returns such a large share of the table that a scan is more sensible.
🧠 A Compact Mental Model
Think of a B-tree as a hierarchy of sorted directory pages. The top pages tell you which large region contains a value; lower pages narrow that region; leaf pages hold the final entries in order.
When data changes, the tree splits crowded pages and repairs underfilled ones so that all paths remain similarly short. When a query needs a range, it finds the starting point and walks forward through neighboring leaf entries.
The core principle is simple: B-trees trade a small amount of structured maintenance for consistently efficient, ordered access to data too large to inspect row by row.
That trade-off is why B-trees remain foundational in database systems. They turn massive collections into navigable, ordered paths—fast enough for everyday searches, flexible enough for changing data, and practical enough for real storage hardware. 💻🌳📚
