HASH Index (Equality Lookups Only)
Last updated: 2026-11-04
HASH Index (Equality Lookups Only)
A HASH index hashes keys into fixed-length buckets. It supports equality lookups (=, IN) only — no range scans, no ordering, and no unique constraints. Because entries are not sorted within a bucket, it cannot provide ordered output and cannot speed up ORDER BY. The PostgreSQL documentation explicitly recommends B-tree over HASH for virtually all workloads.
| Kind | index |
|---|---|
| Example Language | SQL |
📝 Syntax
CREATE INDEX <index_name> ON <table_name> USING hash ( <column> )
⚙️ Parameters
| index_name | Name of the new index. |
|---|---|
| table_name | The table to index. |
| column_name | The indexed column; it must have a hash operator class available (typically text or integer types). |
Returns:No return value. On success the command tag is CREATE INDEX.
▶ Example
Runs real PostgreSQL 18 right in your browser (PGlite WASM, nothing to install). Press ▶ Run and the result appears in the panel below.
Output:
CREATE TABLE
INSERT 0 20000
CREATE INDEX
ANALYZE
-- First EXPLAIN: the equality predicate uses the HASH index
Index Scan using idx_hash_token on idx_demo_hash (cost=0.00..8.02 rows=1 width=4)
Index Cond: (token = 'a1d0c6e83f027327d8461063f4ac58a6'::text)
Index Searches: 1
Buffers: shared hit=3
Planning Time: 0.150 ms
Execution Time: 0.176 ms
-- Second EXPLAIN: hits has no index, so the range predicate triggers a seq scan
Aggregate (cost=487.55..487.56 rows=1 width=8)
-> Seq Scan on idx_demo_hash (cost=0.00..487.00 rows=220 width=0)
Filter: ((hits >= 10) AND (hits <= 20))
Rows Removed by Filter: 19780
Buffers: shared hit=187
Planning Time: 0.068 ms
Execution Time: 1.075 ms
(The EXPLAIN plans above come from a real PostgreSQL 18.6 run; actual time / Planning Time / Execution Time are indicative values and vary with machine load.)
📌 Key Points
- A HASH index only handles equality; range predicates (>, <, BETWEEN) and ordering cannot use it.
- The official docs advise using B-tree unless you have a specific reason — it covers every HASH use case and more.
- HASH indexes cannot back a unique constraint; UNIQUE requires a B-tree index.
- Hash indexes were not crash-safe before PostgreSQL 10. That is fixed now, but the type is still discouraged.
💡 Related Cases
More case studies coming soon.
📚 Related Reference
❓ FAQ
QIf B-tree handles everything, why keep HASH indexes at all?
AMostly historical, plus a niche where a hash table's memory footprint and constant-time lookup can pay off under very large volumes of equality lookups. For almost every project, use B-tree.
QDoes a HASH index slow down writes?
AYes. Every index must be maintained on INSERT / UPDATE / DELETE; a HASH index computes the hash and locates a bucket on each write. The more indexes a table has, the slower writes get.