tezvyn:

B-Tree: The Workhorse of Database Indexes

AI-drafted, machine-checkedSource: Wikipedia: B-treebeginner

A B-tree is a self-balancing tree that keeps data sorted for fast lookups, generalizing a binary search tree by allowing nodes to have many children. It enables searches, insertions, and deletions in logarithmic time, making it ideal for large datasets.

WHY IT EXISTS To solve the problem of storing large, sorted datasets that need to be searched and modified quickly. Simpler data structures force a trade-off: sorted arrays are fast to search but slow to modify, while linked lists are easy to modify but slow to search. B-trees provide efficient, logarithmic time performance for all major operations.

THE MENTAL MODEL A B-tree is a generalization of a binary search tree. While a binary tree node asks a simple "less than or greater than?" question and branches to one of two children, a B-tree node holds multiple sorted keys and can branch to many different children. This creates a tree that is much wider and shorter, or "bushier," than a binary tree with the same number of elements.

HOW IT WORKS A B-tree maintains data in sorted order across all its nodes. When you search for a value, you start at the root and use the sorted keys within the node to decide which child pointer to follow. This multi-way branching is repeated until you find the value or reach a leaf node. The structure is "self-balancing," meaning that as you insert or delete data, the tree automatically restructures itself to maintain its balance. This guarantees that the tree's height remains logarithmic relative to the number of items, ensuring that all operations remain fast even as the dataset grows very large.

WHEN TO USE IT It is the ideal structure for systems that need to maintain a large, dynamic collection of sorted data. Its logarithmic time complexity for searches, sequential access, insertions, and deletions makes it a powerful, general-purpose choice, which is why it's the default for most database indexes.

WHEN NOT TO USE IT For small or completely static datasets that never change, a simpler structure like a sorted array might be sufficient and more memory-efficient. The overhead of a B-tree's balancing mechanism and more complex node structure is unnecessary if the data is read-only.

ONE CANONICAL EXAMPLE While the abstract concept is from computer science, its most widespread, practical application is for implementing the indexes in most relational databases. When you add an index to a database column to speed up queries, you are almost always creating a B-tree under the hood to manage the pointers to your data.

Read the original → en.wikipedia.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.