Sub topic 14
Hash, GIN, GiST, BRIN, and Other Index Types
This chapter assumes you know how a B-tree index works, including point lookups, range scans, and composite indexes. It also assumes you can read basic EXPLAIN output. Examples use PostgreSQL syntax. Other databases offer some of these types under different names, and the chapter notes where.
Why B-tree is not always the answer
A B-tree needs values that can be sorted. It answers "equal to", "less than", "between", and "ordered by". That covers most queries on numbers, text, and timestamps.
Some questions do not fit that model:
- Does this JSON document contain the key-value pair
"type": "signup"? - Does this array include the tag
postgres? - Which text values contain the substring
smith? - Which bookings overlap this time range?
- Which points lie near this location?
- Which rows in a 500 GB append-only table fall in last Tuesday?
A B-tree cannot answer the first four, because those values have no useful single sort order. For the last, a B-tree can answer it but costs far more space than it needs to. PostgreSQL provides other index access methods for these cases. You choose one with USING in CREATE INDEX. When you omit USING, PostgreSQL builds a B-tree.
| Type | Best for | Supports ranges and ordering | Typical size |
|---|---|---|---|
| B-tree | Equality, ranges, sorting | Yes | Medium to large |
| Hash | Equality only | No | Medium |
| GIN | Containment in composite values (arrays, JSON, full text, trigrams) | No | Large |
| GiST | Overlap, nearness, geometry, exclusion constraints | Nearest-neighbor ordering | Medium |
| SP-GiST | Partitioned data such as tries and quadtrees | Limited | Medium |
| BRIN | Huge tables whose physical order follows the column | Coarse ranges | Tiny |
Hash indexes
A hash index stores a hash code of each value and the location of matching rows. It supports only the = operator.
CREATE TABLE sessions (
id bigint PRIMARY KEY,
token text NOT NULL,
user_id bigint NOT NULL,
expires_at timestamptz NOT NULL
);
CREATE INDEX sessions_token_hash_idx ON sessions USING hash (token);
EXPLAIN SELECT * FROM sessions WHERE token = 'f3a9c1e07b';The index never stores the original text, so long keys such as URLs or tokens do not make it large. A lookup needs one hash computation and a bucket probe, not a descent through tree levels. In practice the speed advantage over a B-tree is usually small.
The limits are significant:
- It cannot serve
<,>,BETWEEN, orORDER BY. - It cannot enforce
UNIQUE, and it cannot be a primary key. - It cannot be a multi-column index.
- Before PostgreSQL 10, hash indexes were not crash-safe, which is why older advice says to avoid them. Since version 10 they are WAL-logged and safe to use.
GIN: indexing the contents of a value
GIN stands for Generalized Inverted Index. A normal index maps a row to one key. An inverted index maps each element found inside values to the list of rows that contain it. This is the structure behind full-text search engines.
CREATE TABLE events (
id bigint PRIMARY KEY,
payload jsonb NOT NULL,
tags text[] NOT NULL DEFAULT '{}',
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX events_payload_gin_idx ON events USING gin (payload);
CREATE INDEX events_tags_gin_idx ON events USING gin (tags);
-- JSONB containment
SELECT id FROM events WHERE payload @> '{"type": "signup"}';
-- Array overlap
SELECT id FROM events WHERE tags && ARRAY['postgres', 'indexing'];The operators @> (contains), <@ (is contained by), && (overlaps), and @@ (text search match) are the ones GIN accelerates. A query written with payload ->> 'type' = 'signup' does not use the index above. It needs a B-tree expression index on (payload ->> 'type'). Write the query to match the operator class.
GIN also powers substring search through the pg_trgm extension, which indexes three-character fragments of the text:
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE TABLE users (
id bigint PRIMARY KEY,
email text NOT NULL
);
CREATE INDEX users_email_trgm_idx ON users USING gin (email gin_trgm_ops);
-- A leading wildcard can use this index; a B-tree cannot help here.
SELECT * FROM users WHERE email LIKE '%smith%';GIN trade-offs
- Lookups for containment are fast, but one row may add many index entries, so writes are slower and the index is large.
- PostgreSQL softens write cost with a pending list. New entries go into an unsorted buffer and merge into the main structure in batches (
fastupdate). Queries must scan the pending list too, so a large backlog slows reads until vacuum or a size limit flushes it. - Common elements such as a tag present in 80% of rows give the index little power. The planner may then prefer a sequential scan.
GiST: a framework for "nearby" and "overlapping"
GiST stands for Generalized Search Tree. It is a balanced tree template. Each data type supplies its own rules for grouping values and testing whether a branch might contain a match. This lets one structure handle geometry, ranges, and nearest-neighbor search. The PostGIS extension builds its spatial indexes on it.
A common use is preventing overlapping ranges with an exclusion constraint. A unique constraint says "no two rows are equal". An exclusion constraint says "no two rows conflict under this operator", and PostgreSQL enforces it through a GiST index.
CREATE EXTENSION IF NOT EXISTS btree_gist;
CREATE TABLE bookings (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
room_id integer NOT NULL,
during tstzrange NOT NULL,
EXCLUDE USING gist (room_id WITH =, during WITH &&)
);
INSERT INTO bookings (room_id, during)
VALUES (1, tstzrange('2026-06-01 09:00+00', '2026-06-01 10:00+00'));
-- Fails: same room, overlapping time range.
INSERT INTO bookings (room_id, during)
VALUES (1, tstzrange('2026-06-01 09:30+00', '2026-06-01 11:00+00'));
-- The same index also speeds up overlap searches.
SELECT * FROM bookings
WHERE during && tstzrange('2026-06-01 00:00+00', '2026-06-02 00:00+00');The btree_gist extension lets GiST handle plain equality on room_id alongside the range column. Without it, mixing an integer and a range in one GiST index fails.
GiST indexes can be lossy. The index may return candidate rows that turn out not to match, so PostgreSQL rechecks them against the table. You may see Recheck Cond in a plan. This is normal. A GiST index is also the usual choice for ordering by distance with an operator like <->.
SP-GiST is a sibling that splits the space into non-overlapping regions. It suits data with natural partitions, such as phone number prefixes, IP ranges, or points that cluster.
BRIN: tiny indexes for naturally ordered data
BRIN stands for Block Range Index. It does not record individual rows. For each group of adjacent table pages (128 by default) it stores the minimum and maximum value in that group. A query skips every group whose range cannot match.
CREATE TABLE measurements (
sensor_id integer NOT NULL,
recorded_at timestamptz NOT NULL,
reading double precision NOT NULL
);
CREATE INDEX measurements_recorded_brin_idx
ON measurements USING brin (recorded_at) WITH (pages_per_range = 32);
SELECT avg(reading) FROM measurements
WHERE recorded_at >= '2026-03-01' AND recorded_at < '2026-03-02';A BRIN index on a billion-row table can take a few hundred kilobytes, where a B-tree would take tens of gigabytes. The condition is physical correlation: the column's values must roughly follow the order of rows on disk. Append-only logs and time-series tables inserted in time order fit. A table where recorded_at values are scattered randomly across pages gives every block range a wide min and max, and the index excludes nothing.
You can check correlation from the statistics:
SELECT attname, correlation
FROM pg_stats
WHERE tablename = 'measurements' AND attname = 'recorded_at';A value near 1 or -1 suggests BRIN will work. A value near 0 means it will not. Smaller pages_per_range values give finer filtering at the cost of a larger index.
Other index types and other databases
- Bloom (a PostgreSQL extension) stores a compact signature per row. It suits tables with many columns queried in arbitrary equality combinations, at the cost of false positives.
- MySQL InnoDB offers B-tree indexes,
FULLTEXTindexes, andSPATIALindexes. It builds an adaptive hash index in memory automatically, and you do not create it. - SQL Server adds columnstore indexes for analytic scans, and Oracle has bitmap indexes for low-cardinality columns.
The names differ, but the same question applies. What operations does the query use, and which structure answers them with the least work?
Common errors
- Using the wrong operator. A GIN index on
payloaddoes not helppayload ->> 'type' = 'x'. Check withEXPLAIN. - Adding GIN to a write-heavy table without measuring. Each insert touches many index entries.
- Using BRIN on uncorrelated data. It builds without complaint and then filters nothing.
- Forgetting the extension.
gin_trgm_opsneedspg_trgm, and mixed GiST equality needsbtree_gist. - Expecting a hash index to enforce uniqueness. Use a B-tree
UNIQUEindex.
Exercise
A 2 TB append-only table access_log has a logged_at timestamptz column filled in arrival order. Analysts run daily queries such as WHERE logged_at >= '2026-05-01' AND logged_at < '2026-05-02'. Another query looks for rows where the labels text[] column contains 'error'. Which index type would you choose for each query, and what would you check first for the first one?
Show answer
Use BRIN on logged_at. Rows arrive in time order, so values correlate with physical position, and a BRIN index stays tiny where a B-tree on 2 TB of data would be huge. Before building it, check correlation for logged_at in pg_stats, which should be near 1. Use a GIN index on labels for the @> or && containment query, written as labels @> ARRAY['error'], and accept the extra write cost.