A deep dive into B-Trees, Hash Tables, Bitmaps, and beyond
By The Coding Gopher
Published: 2026-07-23
URL: https://thecodinggopher.substack.com/p/database-indexing-structures-explained
Understanding B-Trees, Hash Tables, Bitmaps, and the engineering trade-offs of read optimization.
In relational database systems, querying an unindexed table requires a Full Table Scan. The database engine must sequentially read every row from the physical disk to find matching records, resulting in O(n) time complexity. For tables containing millions of rows, the disk I/O required for these sequential reads becomes a severe performance bottleneck.
A full table scan is slow for reading from disk primarily because it involves reading every single data block in the table, which for large tables results in a high number of disk I/O operations and often requires inefficient random disk access.
To mitigate this, databases utilize Indexesโauxiliary data structures designed to optimize data retrieval speeds. By creating a mapped reference to the underlying table, indexes reduce the amount of data the engine needs to scan.
Here is a technical breakdown of how primary indexing structures operate at the infrastructure level and the engineering trade-offs they introduce.
1. The B+ Tree Index
When a standard index is created in a relational database like PostgreSQL or MySQL, the engine typically implements a B+ Tree (a variant of the B-Tree).
A B+ tree is a self-balancing, m-ary tree data structure used primarily in databases and file systems to maintain sorted data for fast retrieval. It is an extension of the B-tree where all actual data resides exclusively in the leaf nodes, while internal nodes only hold keys for routing. Leaves are linked together, making it highly efficient for range queries.
A B+ Tree is a self-balancing, hierarchical data structure that maintains sorted data and allows for searches, sequential access, insertions, and deletions in logarithmic time.
The architecture of a B+ Tree consists of three node types:
-
Root Node: The top-level entry point containing search keys and pointers to the next level.
-
Branch Nodes: Internal nodes that further divide the search space.
-
Leaf Nodes: The bottom layer of the tree. In a B+ Tree, the actual pointers to the physical rows on the disk (or the row data itself, in clustered indexes) are stored exclusively in the leaf nodes.
Performance and Range Queries
The B+ Tree is strictly balanced, meaning every path from the root to a leaf node has the exact same depth. This guarantees a predictable time complexity of O(log n) for lookups.
Furthermore, the leaf nodes in a B+ Tree are connected via a doubly-linked list. This architecture makes the B+ Tree highly optimized for Range Queries. If an application executes a query like WHERE age BETWEEN 20 AND 30, the database engine traverses the tree to find 20 in O(log n) time, and then sequentially traverses the linked leaf nodes to retrieve the rest of the range.
Range queries in a B+ tree are highly efficient because the data structure stores all actual records in the leaf nodes, which are linked together in a sorted sequence. This allows the tree to find the start of a range quickly and then simply "walk" through the data until the end of the range is reached.
๐๐๐๐ซ๐ง ๐ญ๐จ ๐๐ฎ๐ข๐ฅ๐ ๐๐ข๐ญ, ๐๐จ๐๐ค๐๐ซ, ๐๐๐๐ข๐ฌ, ๐๐๐๐ ๐ฌ๐๐ซ๐ฏ๐๐ซ๐ฌ, ๐๐ง๐ ๐๐จ๐ฆ๐ฉ๐ข๐ฅ๐๐ซ๐ฌ, ๐๐ซ๐จ๐ฆ ๐ฌ๐๐ซ๐๐ญ๐๐ก. Get 40% OFF CodeCrafters: https://app.codecrafters.io/join?via=the-coding-gopher
This Substack is reader-supported. To receive new posts and support my work, consider becoming a free or paid subscriber.
2. The Hash Index
While B+ Trees are highly versatile, databases also employ Hash Indexes for specific, narrow workloads.
A Hash Index uses a mathematical hashing function to map search keys (e.g., a session token) directly to specific memory buckets where the corresponding row pointers are stored.
-
The Advantage: Hash indexes provide O(1) constant-time lookups. The time required to locate a record is mathematically independent of the tableโs total size, making them highly efficient for exact equality matches (WHERE token = 'abc').
-
The Limitation: Hash functions obfuscate the natural order of the data. Consequently, hash indexes cannot evaluate ranges (>, <), perform partial/prefix matches, or assist with sorting operations (ORDER BY). If an application attempts a range query on a hash-indexed column, the database must revert to a full table scan.
A hash index is a database data structure designed for ultra-fast data retrieval (with O(1) complexity) using a hash function to map keys directly to specific buckets (data locations). It is highly efficient for exact-match queries (SELECT * FROM table WHERE column = 'value') but, unlike B-trees, cannot perform range scans or sorting.
3. The Bitmap Index
When dealing with massive data warehouses and analytical workloads (OLAP), B+ Trees can become highly inefficient for specific types of data. This is where the Bitmap Index comes in.
Instead of storing a list of row pointers for every value, a bitmap index uses an array of bits (0s and 1s). Each bit mathematically corresponds to a specific row in the table. If the row possesses the indexed value, the bit is set to 1; if not, it is set to 0.
-
The Advantage: Bitmap indexes are incredibly space-efficient for low-cardinality data (columns with very few distinct values, such as isactive, gender, or subscriptiontier). Furthermore, if a query includes multiple conditions (WHERE is_active = true AND tier = 'premium'), the database CPU can perform native, low-level bitwise AND/OR operations across multiple bitmaps to find the matching rows with blinding speed.
-
The Limitation: Bitmap indexes are catastrophic for transactional (OLTP) environments with high-frequency writes. Updating a single rowโs value often requires the database engine to lock the entire bitmap vector to prevent corruption, completely halting concurrent write operations from other users.
Bitmap indexes are specialized database structures that use arrays of bits (0s and 1s) to rapidly filter large, read-heavy datasets with low-cardinality columns (few unique values, e.g., gender, status). They excel in data warehousing and analytics by enabling fast bitwise AND/OR operations, significantly reducing query response times compared to B-trees.
4. The Engineering Trade-offs. The Write Penalty
A common anti-pattern in database design is over-indexing. Indexes are independent data structures that require physical compute and storage resources to maintain. Every index added to a schema introduces significant architectural trade-offs:
Database indexes are specialized data structures that function like the index of a book. Instead of forcing the database to scan every single row in a table to find specific information, an index provides a direct map to the exact location of the data, drastically speeding up search and retrieval times.
-
Storage Overhead: Indexes consume disk space. Indexing multiple columns on a massive table can easily double or triple the total storage footprint of the database.
-
The Write Penalty: Indexes degrade write performance. Whenever an INSERT, UPDATE, or DELETE operation is executed against the base table, the database engine must synchronously update the base data and every single index associated with that table. For B+ Trees, this includes the computational overhead of mathematically rebalancing the tree structure.
In a high-throughput transactional database, applying too many indexes will severely bottleneck write operations.
Strategy Summary
Optimizing a database schema requires selecting the appropriate index type based on query patterns while strictly limiting the total number of indexes to preserve write latency.
-
B+ Tree: Delivers O(log n) time complexity. It is optimal for general purpose queries, sorting (ORDER BY), and range queries (>,<, BETWEEN), but is inefficient for full-text search across large text blobs.
-
Hash: Delivers O(1) time complexity. It is optimal for high-frequency exact equality matches (=), but cannot process sorting, ranges, or prefix matching.
-
Bitmap: Utilizes fast bitwise operations. It is optimal for low-cardinality data (e.g., boolean flags, fixed categories) in analytical workloads, but causes severe concurrency bottlenecks and performance degradation on tables with high-frequency writes.
This Substack is reader-supported. To receive new posts and support my work, consider becoming a free or paid subscriber.
Thanks for reading! This post is public so feel free to share it.
