Sub topic 2
Hash indexes: equality lookups only
This chapter assumes you know basic SQL (SELECT, WHERE, ORDER BY), can create tables in PostgreSQL, and can run EXPLAIN. You should also be familiar with B-tree indexes, the default index type.
A hash index stores a fixed-size hash of each indexed value and uses it to find matching rows. It supports only the = operator. It cannot serve range filters, ORDER BY, or unique constraints.
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);
EXPLAIN SELECT id FROM sessions WHERE token = 'abc123';Use a hash index only when the column is queried almost exclusively by equality. A B-tree also handles equality well and serves ranges and sorting, so measure the gain before choosing hash. Since PostgreSQL 10, hash indexes are WAL-logged, so they survive crashes safely.
Operator classes: matching an index to your operators
An operator class lists the operators an index type can serve for a given data type. The default class for text in a B-tree is text_ops. Under a non-C locale, it cannot serve a left-anchored LIKE, so use text_pattern_ops for that case.
CREATE INDEX people_name_pattern_idx
ON people (name text_pattern_ops);For substring searches such as ILIKE '%smith%', install the pg_trgm extension and use gin_trgm_ops.
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE INDEX people_name_trgm_idx
ON people USING gin (name gin_trgm_ops);> Hmm
GIN: indexing jsonb, arrays, and full-text search
A GIN (Generalized Inverted Index) maps each key, element, or word to the rows that contain it. It fits containment queries on jsonb, array columns, and full-text search.
CREATE INDEX events_payload_gin_idx
ON events USING gin (payload);
SELECT id FROM events WHERE payload @> '{"type": "login"}';GIN writes are slower than B-tree writes, because one row touches many index entries.
GiST: geometry, ranges, nearest-neighbor search, and exclusion constraints
GiST (Generalized Search Tree) is a framework for geometric and range data. It supports distance ordering with <->.
CREATE INDEX places_location_gist_idx
ON places USING gist (location);
SELECT id, name
FROM places
ORDER BY location <-> point '(10, 20)'
LIMIT 5;GiST also backs exclusion constraints. The following constraint rejects overlapping bookings for the same room. The btree_gist extension lets GiST handle the integer equality part.
CREATE EXTENSION IF NOT EXISTS btree_gist;
CREATE TABLE reservations (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
room_id integer NOT NULL,
during tstzrange NOT NULL,
CONSTRAINT no_double_booking
EXCLUDE USING gist (room_id WITH =, during WITH &&)
);Exercise
Why can a hash index not speed up ORDER BY token on the sessions table?
Show answer
A hash index stores hash values, which have no sort order, and it supports only the = operator. Use a B-tree index for ordering.