Course contentsShow
← Databases & SQL
Lesson 640 of 1,9536. Query Performance and IndexingFree lesson

Hash Indexes vs B-Trees

Contrast the O(1) average lookup of hash indexes with the O(log N) range-scan ability of B-trees.

In this lesson, you will learn why choosing between a Hash Index and a B-Tree depends on whether you need lightning-fast equality lookups or the flexibility of ordered data retrieval.

The Power of the Hash Index

A Hash Index is built for pure speed when you are searching for an exact match. It uses a hash function to compute a "bucket" address for each value, allowing the database to jump directly to the data.

Because the database doesn't have to traverse a tree structure, lookups typically take O(1) (constant) time. It is effectively a shortcut: "I know exactly where this ID is, so I’ll go straight there." However, the trade-off is significant: Hash Indexes are unordered. If you try to perform a range scan (like WHERE age > 20), the index is useless because the data isn't sorted in any logical way. The database would be forced to perform a full table scan instead.

The Flexibility of the B-Tree

The B-Tree is the "Swiss Army Knife" of indexing. It organizes data in a hierarchical, sorted tree structure. When you search for a value, the database traverses the tree from the root down to the leaves, which takes O(log N) time.

While O(log N) is technically slower than O(1), it grants you a superpower: Range Scans. Because the leaf nodes are connected in a sorted sequence, the database can efficiently find a starting point and then simply "walk" along the leaves to retrieve a range of data:

-- This range query is perfect for a B-Tree
SELECT * FROM Orders 
WHERE OrderDate BETWEEN '2023-01-01' AND '2023-01-31';

A Hash Index would fail here because it cannot identify "betweenness." The B-Tree, however, thrives by quickly narrowing down the range and reading the contiguous blocks of sorted records.

Summary Comparison

  • Hash Index: Best for WHERE ID = 123. It is a high-speed, direct lookup that breaks down the moment you need to sort or filter by ranges.
  • B-Tree: The balanced standard. It is slightly slower for individual lookups but essential for range queries, sorting, and grouping.

Key Takeaway: Use a Hash Index for O(1) point lookups when equality is your only need, but rely on B-Trees for their O(log N) efficiency and their vital ability to handle range-based queries.