Difficulty: Intermediate
Why is the B-tree the default index type in most relational databases instead of a hash index?
A B-tree keeps keys in sorted order, so a single index can answer equality lookups, range filters (>, <, BETWEEN), prefix searches, ORDER BY, MIN and MAX, all in O(log n) time. A hash index only answers exact equality (=) in roughly O(1) time and cannot help with anything that depends on order. Because B-trees cover nearly every query pattern well, databases make them the default and treat hash indexes as a niche option.
A B-tree (in practice a B+tree) is a shallow, balanced tree of fixed-size pages:
created_at BETWEEN '2026-01-01' AND '2026-01-31', the database finds the first matching leaf and then scans sideways through linked leaves.Because keys are sorted, a query with ORDER BY created_at LIMIT 20 can read the first 20 entries and stop without sorting.
A hash function maps each key to a bucket. To find email = 'a@x.com', the database hashes the value and goes straight to that bucket. Hashing destroys order: 'a@x.com' and 'b@x.com' land in unrelated buckets, so the index is useless for ranges, sorting or LIKE 'abc%'.
| Capability | B-tree | Hash |
|---|---|---|
Equality = | Yes, O(log n) | Yes, about O(1) |
Range <, >, BETWEEN | Yes | No |
ORDER BY without sorting | Yes | No |
Prefix LIKE 'abc%' | Yes (in PostgreSQL may need text_pattern_ops or C collation) | No |
| Multi-column, leftmost prefix | Yes | Limited or no |
| Unique constraint | Yes | Not in PostgreSQL |
CREATE INDEX ... USING hash exists. Before PostgreSQL 10 hash indexes were not WAL-logged, so they were not crash safe or replicated; since v10 they are. They support only single-column equality and cannot be unique.USING HASH is accepted but a B-tree is built. InnoDB does have an internal adaptive hash index that it builds automatically over hot B-tree pages. The MEMORY engine supports true hash indexes.| B-tree | Hash | |
|---|---|---|
| WHERE id = 5 | Yes | Yes |
| WHERE age > 18 | Yes | No |
| ORDER BY created_at LIMIT 20 | Yes, no sort needed | No |
| WHERE name LIKE 'Ra%' | Yes | No |
-- Default: B-tree
CREATE INDEX idx_orders_created ON orders (created_at);
-- Hash: equality only
CREATE INDEX idx_sessions_token ON sessions USING hash (token);
-- Uses the B-tree for a range plus ordering
EXPLAIN SELECT * FROM orders
WHERE created_at >= '2026-10-01'
ORDER BY created_at LIMIT 20;
-- Uses the hash index
EXPLAIN SELECT * FROM sessions WHERE token = 'abc123';
-- Cannot use the hash index: falls back to a scan
EXPLAIN SELECT * FROM sessions WHERE token > 'abc';
Run EXPLAIN to see which index the planner picks. The last query shows a hash index cannot serve a range predicate.
B-Tree Index, Hash Index, Range Queries, Index Ordering, Adaptive Hash Index