Sub topic 5
Hash indexes: equality lookups only
Prerequisites and the basic idea
This chapter assumes that you can write basic SQL with SELECT, WHERE, and ORDER BY, create PostgreSQL tables, and recognize common types such as integer and text.
A hash index stores a hash value derived from each indexed value. A hash function converts a value such as 'abc123' into a fixed-size number. PostgreSQL uses that number to find the index bucket that may contain matching rows.
Hash indexes are designed for one operation: equality comparison with =.
CREATE TABLE sessions (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
token text NOT NULL
);
INSERT INTO sessions (token)
SELECT md5(g::text)
FROM generate_series(1, 100000) AS numbers(g);
CREATE INDEX sessions_token_hash_idx
ON sessions USING hash (token);
ANALYZE sessions;
EXPLAIN (ANALYZE, BUFFERS)
SELECT id
FROM sessions
WHERE token = md5('42000'::text);The query compares token with one value using =. A hash index can locate the bucket for that value and then check the candidate rows. The index does not store the original ordering of the values, so it cannot provide results in alphabetical or numerical order.
What a hash index supports
The important distinction is the operator used by the query:
| Query condition | Hash index can support it? |
|---|---|
| `token = 'abc123'` | Yes |
| `token <> 'abc123'` | No |
| `token > 'abc123'` | No |
| `token BETWEEN 'a' AND 'm'` | No |
| `ORDER BY token` | No |
A hash index can support equality lookups on its indexed expression. It does not support range searches, ordering, or prefix searches. For example, it cannot directly accelerate token LIKE 'abc%'.
A hash index also does not make a query fast merely because the query contains =. PostgreSQL's planner estimates the cost of several possible plans. It considers the number of matching rows, table size, statistics, cache state, and the cost of accessing the index and table. On a small table, a sequential scan can be cheaper than any index scan.
How hash indexes differ from B-trees
B-tree is PostgreSQL's general-purpose default. It supports equality, range comparisons, and ordering. Therefore, a B-tree is usually the better choice when the workload may grow to include more than equality lookups.
A hash index can be reasonable when all of these conditions hold:
- The workload is dominated by equality comparisons.
- The indexed value has no useful ordering requirement.
- You have measured the workload and confirmed that a hash index helps.
- You do not need a unique index on the column.
Hash indexes cannot enforce uniqueness. If a column must contain unique values, use a UNIQUE constraint or a unique B-tree index. PostgreSQL's primary key and ordinary unique constraints use B-tree indexes by default.
Reading the plan
In the example, look for a plan node such as Index Scan or Bitmap Index Scan that names sessions_token_hash_idx. EXPLAIN (ANALYZE, BUFFERS) adds actual execution timing and buffer activity to the estimated plan.
If the plan says Seq Scan, PostgreSQL chose to read the table directly. That is not proof that the index is broken. The table might be too small, the condition might match too many rows, or statistics might be stale.
Run ANALYZE after loading a large amount of data. Then inspect the plan again. Do not force an index just to make the plan mention it. A forced plan can hide the fact that a sequential scan is the cheaper choice.
Choosing between hash and B-tree
Start with a B-tree unless the workload gives you a clear reason to choose another type. A B-tree handles equality lookups and also leaves room for future range and ordering queries.
Consider a hash index only after testing a representative workload. Compare execution plans and timings with realistic data. Remember that every additional index increases insert, update, vacuum, storage, and backup costs.
Exercise
Can a hash index efficiently support WHERE customer_id >= 1000 or ORDER BY customer_id? What index type is the usual alternative?
Show answer
No. Hash indexes support equality lookups only. A B-tree is the usual alternative because it supports equality, range comparisons, and ordering.