Sub topic 5
Hash indexes: equality lookups only
This chapter assumes you can read basic EXPLAIN output and know what a B-tree index is, as covered in the earlier chapters. You should also be comfortable creating tables and inserting rows in PostgreSQL. By the end you will know what a hash index stores, which queries it serves, which it cannot serve, and when it is worth choosing over a B-tree.
What a hash index stores
A hash index does not store your column values. For each row it stores a 4-byte hash code computed from the indexed value, plus the row's tuple identifier (TID, the physical location of the row in the table). To look up a key, PostgreSQL does the following:
- It hashes the search value with the hash function for the column's type.
- It uses the hash code to pick one bucket, which is a page, or a short chain of pages, in the index.
- It reads the TIDs stored under that hash code.
- It fetches those rows from the table and checks that the real value matches.
Step 4 is needed because two different values can produce the same hash code. The index is therefore lossy: it narrows the search to candidates and the table row has the final say. The planner handles this for you. You may see Recheck Cond in a bitmap scan plan.
Internally the index has these page types:
- A metapage that records how many buckets exist.
- Bucket pages that hold the entries.
- Overflow pages that are chained on when a bucket fills up.
- Bitmap pages that track which overflow pages are free.
The index grows by linear hashing. When the average fill gets too high, PostgreSQL splits one bucket at a time instead of rebuilding the whole structure.
Creating one
Use USING hash:
CREATE TABLE sessions (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
token text NOT NULL
);
CREATE INDEX sessions_token_hash_idx
ON sessions USING hash (token);
SELECT id FROM sessions WHERE token = 'abc123';The condition token = 'abc123' can use the index. These conditions cannot:
token > 'abc'token LIKE 'abc%'ORDER BY tokentoken IS NULL
The hash code carries no information about order or prefix. Hash codes of similar strings are unrelated, so the index cannot answer "everything between X and Y." Hash indexes also do not store NULLs in a searchable way, so IS NULL needs a different index or a scan.
Where a hash index can win: long keys
A B-tree stores the full key in every entry. For long strings such as URLs, tokens, or file paths, the B-tree becomes large. A hash index entry holds only the 4-byte hash code and a TID, so its size does not depend on key length. This also removes the B-tree limit on entry size, which is roughly a third of a page. A value larger than that cannot be put in a B-tree index, but a hash index can index it.
The script below builds both index types on the same long column so you can compare them. It is complete and runnable.
CREATE TABLE pages (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
url text NOT NULL
);
INSERT INTO pages (url)
SELECT 'https://example.com/articles/' || md5(g::text)
|| '/' || md5((g * 7)::text) || '/index.html'
FROM generate_series(1, 200000) AS g;
CREATE INDEX pages_url_btree_idx ON pages (url);
CREATE INDEX pages_url_hash_idx ON pages USING hash (url);
ANALYZE pages;
SELECT indexrelname,
pg_size_pretty(pg_relation_size(indexrelid)) AS size
FROM pg_stat_user_indexes
WHERE relname = 'pages'
ORDER BY indexrelname;Each URL here is about 105 bytes. The B-tree entries carry that whole value, and the hash entries carry 4 bytes of hash code. Expect pages_url_hash_idx to be clearly smaller than pages_url_btree_idx. The exact sizes depend on your version and settings, so run the script instead of trusting a number from this chapter.
Smaller indexes matter because they are more likely to stay in shared_buffers and the OS cache, and they take less time to write and back up.
Checking that the planner uses it
To see the hash index used, make it the only candidate by dropping the B-tree, then run EXPLAIN:
DROP INDEX pages_url_btree_idx;
EXPLAIN (ANALYZE, BUFFERS)
SELECT id
FROM pages
WHERE url = 'https://example.com/articles/'
|| md5('500') || '/' || md5((500 * 7)::text) || '/index.html';You should see an Index Scan or Bitmap Index Scan on pages_url_hash_idx. The Buffers line shows how few pages were touched compared with a sequential scan of the whole table.
Now try a range condition:
EXPLAIN
SELECT id FROM pages WHERE url > 'https://example.com/articles/f';The plan falls back to a Seq Scan, because the hash index cannot evaluate >.
If you keep both indexes, the planner picks whichever its cost model estimates as cheaper for each query. It is not guaranteed to pick the hash index even when it is smaller. If you want to know which one it uses, check idx_scan in pg_stat_user_indexes after running your workload.
Limitations
The following limits come from how the index is built, and they affect design decisions.
| Capability | B-tree | Hash |
|---|---|---|
| Equality (`=`) | Yes | Yes |
| Range and `ORDER BY` | Yes | No |
| Prefix `LIKE` | Yes, with the right operator class or locale | No |
| `UNIQUE`, primary key | Yes | No |
| Multiple columns | Yes | No |
| `INCLUDE` columns | Yes | No |
| Index-only scans | Yes | No |
| Searching for NULL | Yes | No |
| Size depends on key length | Yes | No |
Attempting an unsupported shape fails at creation time:
-- Both statements fail with an error saying hash does not support
-- unique indexes and multicolumn indexes respectively.
CREATE UNIQUE INDEX sessions_token_uniq ON sessions USING hash (token);
CREATE INDEX sessions_multi_hash ON sessions USING hash (id, token);Two consequences follow:
- You cannot enforce uniqueness with a hash index. If
tokenmust be unique, you still need a unique B-tree. That B-tree can already serve the equality lookup, which removes much of the reason for a separate hash index. - There are no index-only scans. The index holds hash codes, not values, so PostgreSQL must always visit the table row. A B-tree with
INCLUDEcan answer some queries without touching the table, and a hash index never can.
Failure modes
Many duplicates. Every row with the same value has the same hash code and lands in the same bucket. For a low-cardinality column such as status with a few distinct values, the bucket for each value becomes a long chain of overflow pages. Lookups then read most of the chain. A hash index suits columns with many distinct values.
Hash collisions. Different values can share a 4-byte hash code. The cost is a few extra table fetches that fail the recheck. With millions of distinct values this is a small effect, but it is another reason the index never replaces the table check.
Space that does not shrink. Buckets are added as the table grows, but the bucket count does not go back down after deletes. VACUUM removes dead entries and can recycle overflow pages. If a table shrinks sharply, REINDEX is how you get a compact index.
Heavy churn. Hash indexes pay the same per-row write cost as other indexes. Every INSERT adds an entry. An UPDATE adds an entry unless it qualifies as a heap-only tuple (HOT) update. A HOT update requires that no indexed column changes and that there is room on the same page. Updating a hashed column always defeats HOT.
Old versions. Before PostgreSQL 10, hash indexes were not written to the write-ahead log (WAL). They were not crash safe and were not copied to replicas, so advice to avoid them dates from that period. From PostgreSQL 10 onward they are WAL-logged, safe after a crash, and replicated. If you upgraded a database from 9.x with pg_upgrade, rebuild any old hash indexes with REINDEX.
Inspecting a hash index
The pgstattuple extension includes pgstathashindex, which reports on bucket, overflow, and free space:
CREATE EXTENSION IF NOT EXISTS pgstattuple;
SELECT bucket_pages, overflow_pages, live_items, dead_items, free_percent
FROM pgstathashindex('pages_url_hash_idx');A high ratio of overflow_pages to bucket_pages suggests many duplicates or heavy skew. A high dead_items count suggests VACUUM has not caught up. A large free_percent after heavy deletes is a signal to consider REINDEX.
Maintenance
Hash indexes support the same online operations as other index types:
CREATE INDEX CONCURRENTLY sessions_token_hash_idx2
ON sessions USING hash (token);
REINDEX INDEX CONCURRENTLY sessions_token_hash_idx2;CREATE INDEX CONCURRENTLY cannot run inside a transaction block. The fillfactor storage parameter is available, with a default of 75. It controls how full bucket pages are when the index is built.
When to choose a hash index
A B-tree already handles equality well, and its tree depth is small for most tables. The default choice for an equality-only column is therefore a B-tree, especially when you might later need ordering, ranges, or uniqueness. Consider a hash index when all of these hold:
- Every query on the column uses
=and nothing else. - The column has many distinct values.
- The keys are long, so a B-tree on that column is large.
- You do not need uniqueness, multiple columns, or index-only scans on this column.
If you suspect it will help, measure. Build both indexes on a copy of realistic data, compare pg_relation_size, and compare EXPLAIN (ANALYZE, BUFFERS) for your real queries. Keep the hash index only if the difference justifies a second index type in your schema.
Exercise
A table api_keys has a key_text column holding 64-character random strings. Queries only run WHERE key_text = $1, and each key must be unique. Can a hash index alone cover this table's needs? What would you create instead?
Show answer
No. A hash index cannot enforce uniqueness, so it cannot back a UNIQUE constraint or primary key. Create a unique B-tree (CREATE UNIQUE INDEX ... ON api_keys (key_text) or a UNIQUE constraint). It enforces uniqueness and also serves the equality lookup, so a second hash index adds write cost for little gain.
Exercise
You build CREATE INDEX ON orders USING hash (status), where status has four distinct values across 50 million rows. Why is this a poor choice, and which index would you consider if the query is WHERE status = 'open' and only about 1% of rows are open?
Show answer
Each of the four values maps to a single hash code, so millions of entries share one bucket and form very long overflow chains, and each lookup reads most of that chain. A partial B-tree on the selective rows, such as CREATE INDEX ON orders (created_at) WHERE status = 'open' (or on whichever column the query needs), indexes only the roughly 1% of matching rows.
Exercise
A query SELECT url FROM pages WHERE url = '...' uses a hash index on url. Will EXPLAIN ever show an Index Only Scan for it? Why or why not?
Show answer
No. The hash index stores a hash code and a TID, not the column value, so PostgreSQL must always fetch the table row to return url and to recheck the match. Index-only scans are not supported by hash indexes.