Hash indexes
Overview
Hash indexes map a key to a hash code and locate candidate entries through buckets. Collisions require equality verification. PostgreSQL 17 supports native hash indexes for equality, not ordered ranges; SQLite has no native CREATE INDEX USING hash syntax.
First example
SELECT id,id%10 AS bucket FROM ix_order WHERE id IN (42,52) ORDER BY id;Observed SQLite result (rows in JSON):
[ [ 42, 2 ], [ 52, 2 ]]How it works
The first example simulates a collision using id modulo 10: 42 and 52 share a bucket but are distinct keys. This is a conceptual hash model, not an actual native hash access method. The second example uses a real SQLite B-tree equality lookup. PostgreSQL hash indexes do not enforce uniqueness or provide sorted output. Do not assume a hash index outperforms a B-tree; compare workload, data distribution and costs.
Practical example
SELECT id FROM ix_order WHERE ref='Ref0042';Observed SQLite result (rows in JSON):
[ [ 42 ]]Practice and mistakes
Practice: calculate id%10 for 43 and 53. Hint 1: same remainder. Hint 2: verify original key equality. Then inspect a B-tree equality lookup by reference.
PostgreSQL 17 example — NOT RUN
BEGIN;CREATE TEMP TABLE ix_demo(id integer, customer integer, day integer, amount integer, ref text, status text);INSERT INTO ix_demo VALUES (42,2,42,420,'Ref0042','open'),(52,2,52,520,'Ref0052','closed');CREATE INDEX ix_demo_hash ON ix_demo USING hash(ref);SELECT id FROM ix_demo WHERE ref='Ref0042';ROLLBACK;Expected result, not executed: [[42]]