B-Tree vs Hash Index: Which to Use and Why
A hash index finds one exact key. A B-tree also handles ranges, sorting and prefixes, which is why MySQL and PostgreSQL default to B-trees.
In this chapter
Why MySQL picks a B-tree over a hash index
More on Indexes: how queries use them
- Why an Index Lookup Is Still Slow: Key Lookups Explained
- Covering Index in SQL Explained with Examples
- Composite Index and the Leftmost Prefix Rule Explained
- Index Range Scan Explained: BETWEEN, > and < on a B-Tree
- ORDER BY and GROUP BY Using an Index (Avoid Filesort)
- Why Is MySQL Not Using My Index? Common Reasons
Keep learning
Overview
Equality (=, IN) ✓ about 1 probe ✓ height pages Range (<, >, BETWEEN) ✕ full scan ✓ descend once, follow leaves ORDER BY / LIMIT ✕ must sort everything ✓ already in order LIKE 'abc%' MIN / MAX ✓ one edge of the tree Leftmost columns of a composite key ✕ needs every column ✓ any leading prefix Resize rehashes everything Splits one page at a time Where MySQL offers it MEMORY engine (default there is hash), NDB, internal AHI InnoDB, MyISAM, MEMORY (USING BTREE) Two buckets, one directory bit. Each bucket holds two keys. All keys inserted last bits → bucket bits it uses chapters · indexes Why MySQL picks a B-tree over a hash index
1. What each structure can answer
The B-tree is covered in the evolution of structures and clustered and secondary indexes. What matters here: a B-tree's equality lookup costs a handful of page reads (why that handful stays small), and every other lookup in the table rides on the same sorted leaves.
2. Collisions and resizing
The fix for long chains is more buckets, and that is the other cost of hashing. Changing the number of buckets changes where every key belongs, so the whole table is rehashed (some designs, such as extendible hashing, soften this by splitting one bucket at a time, but they still give up ordering). A B-tree grows by splitting the one page that overflowed, and the rest of the tree is untouched.
Growing without rehashing everything: extendible hashing
Static hashing fixes the number of buckets, so growth means rehashing every key. Extendible hashing keeps a small directory indexed by the last few bits of the hash, and several directory entries may point at the same bucket. When a bucket overflows, only that bucket splits, and its keys are divided by one more bit. If the bucket already uses every bit the directory has, the directory doubles first, which only copies pointers. Insert the keys one by one and watch it grow. Static against extendible hashing Static hashing Extendible hashing Number of buckets Fixed when the table is created Grows by splitting one bucket Chains, or probing for a free slot The overflowing bucket splits Cost of growing Rehash every key Move the keys of one bucket, copy the directory at most Best for Small, stable data sets Large, growing data sets Extendible hashing grows gracefully, but it is still equality only. The keys inside the buckets have no order, which is why the B-tree stays the default.
3. InnoDB's adaptive hash index
Watch the SEMAPHORES and INSERT BUFFER AND ADAPTIVE HASH INDEX sections of SHOW ENGINE INNODB STATUS: it prints hash searches per second against non-hash searches. If hash searches are a small share, or the status shows many waits on btr0sea latches, the AHI is costing more than it gives. Turning it off is a dynamic setting, so it is cheap to test. It is memory taken from the buffer pool, and a heavy DROP TABLE or truncate on a big hashed table can stall while its entries are removed.
4. The MEMORY engine, and a hash you build yourself
The other place a hash earns its keep is a long value you only ever compare for equality, such as a URL of several hundred characters. A B-tree entry holding the whole URL is large and shrinks the fan-out. The pattern is a short fixed column next to it:
Reference: hash against B-tree
What each index structure can do Hash index B-tree index PostgreSQL has real USING hash indexes (crash-safe since version 10), but even there the default is a B-tree, for the same reasons: a hash index supports only equality and the B-tree supports equality at similar speed plus everything else.
Recap
A hash index gives about one probe for equality and nothing for ranges, ordering, prefixes, MIN/MAX or a subset of the key's columns. A B-tree costs a few page reads for equality and serves every other lookup from the same sorted leaves, which is why it is the general default. InnoDB's adaptive hash index is automatic, in memory, and good for hot point lookups. Check the hash-search ratio and latch waits before leaving it on for write-heavy or scan-heavy loads.
More courses
- Jobs, linked to lessons — Browse jobs where every requirement links to the chapter that teaches it. See how ready you are, how long the gap takes to close, and which listings look stale.
- Match a job post to courses — Paste a job post. Each skill is matched to a track here and put in learning order, foundations first.
- React patterns from open source — Patterns extracted from Material UI, Radix, React Aria, React Hook Form, Redux Toolkit, TanStack, and Next.js — not slides about hooks.
- System Design — Core concepts first (SQL vs NoSQL, CAP, indexing, replication, sharding), then designs grouped by what carries them: the database, Redis, Kafka, or many services.
- NestJS: build a real API — One ticket-booking API, built in order: a plain Node server first, then NestJS modules, validation, a real database, and the features real clients lean on.
- Microservices — Microservice patterns one diagram at a time: how to split a monolith, how services talk, and how data stays consistent without distributed transactions.
- Kafka — A beginner-to-senior path through event logs, reliable delivery, production operations, and disaster recovery.
- AI engineering for software engineers — Eight free reads, in order, for software engineers moving into AI: when to build an agent, how to build one, how to test it, and how the model works underneath.
- Frontend system design — How a UI is sliced when it is a product, not a page: ownership of state, cache, routes, and what happens when the network lies.
- TypeScript in depth — The type system as a design tool. Inference, narrowing, generics, and the errors that mean the model is wrong — not a catalog of utility types.
- CSS in depth — See the box, then the page. Visual chapters from the box model through Flexbox surprises, Grid, selectors, and units, then backgrounds, shapes, and visual effects, each with a playground.
- Accessibility — Foundations first (WCAG in plain words, semantic HTML, lists, alt text), then hands-on HTML labs, a full pass of WAI-ARIA 1.3, and a final fix-the-page challenge.
- Docker — What an image is, why layers cache, and how containers find each other on a network.
- Redis — Fifteen Redis patterns, one picture each: cache, session, lock, counter, rate limiter, queue, and when Redis is the wrong tool.
- Kubernetes — Kubernetes from zero to operators: why it exists, Pods, Deployments and Services, then configuration, networking, storage, scheduling, scaling and security.
- AWS — AWS networking in plain English. A VPC is a gated housing society: streets are subnets, the Internet Gateway is the main gate, and a route table is the signboard.
- Networking: the NetRoute game — NetRoute is a packet logistics game. You wire up computers, switches, routers, firewalls and gateways, set each device, and watch glowing packets travel. If a packet gets dropped, the game shows you which header field was wrong.