Hash Index Equality Only Lookups

Create a hash index for equality-only lookups on long token columns, leaving range predicates, ordering, and uniqueness to a btree companion index.

SqlData Integrity

Code

snippet
-- 长随机 token 只有等值点查需求:hash 索引只服务 = 比较,通常比 btree 更小
-- PostgreSQL 10 起 hash 索引写入 WAL,崩溃后可恢复
CREATE TABLE sessions (
    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    token text NOT NULL,
    payload text NOT NULL,
    created_at timestamptz NOT NULL DEFAULT NOW()
);

CREATE INDEX sessions_token_hash ON sessions USING hash (token);

-- 等值条件能吃 hash 索引
EXPLAIN (COSTS OFF)
SELECT payload FROM sessions WHERE token = '9f8e7d6c5b4a';

-- 范围、排序、唯一性都不在 hash 索引能力内,这些仍需要 btree
CREATE INDEX sessions_token_btree ON sessions (token);

SELECT id, token FROM sessions
WHERE token >= '9f8e00000000'
ORDER BY token
LIMIT 10;

How the snippet works

Several statements share this file — SELECT / CREATE / EXPLAIN, with sessions among the objects involved.

Mechanically, the statements are built from: a WHERE clause narrowing which rows one statement affects; an ORDER BY that fixes the output order; a row cap (LIMIT) bounding the result size; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; DEFAULT values filling omitted columns; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.

Using it

Point it at the sessions table — the LIMIT keeps the probe cheap while you tune the predicates.

Key statements

SELECT id, token FROM sessions
WHERE token >= '9f8e00000000'
ORDER BY token
LIMIT 10;
EXPLAIN (COSTS OFF)
SELECT payload FROM sessions WHERE token = '9f8e7d6c5b4a';
CREATE TABLE sessions (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
token text NOT NULL,
payload text NOT NULL,
created_at timestamptz NOT NULL DEFAULT NOW()
);

Interactive Tools for This Topic

FAQ

Name the tables involved in this file.
`sessions`.