Video in progress
Besides B-tree, when do you choose GIN, GiST and BRIN indexes?
Good for / Example — B-tree: equality, ranges, sorting / id, email, created_at; GIN: "is the element inside" / tags @> '{java}', JSONB, tsvector, pg_trgm; GiST: overlap, distance / tstzrange, PostGIS, EXCLUDE constraint; BRIN: a column correlated with physical order / created_at in an append-only log
📖 Answer
| Index | Good for | Example |
|---|---|---|
| B-tree | equality, ranges, sorting | id, email, created_at |
| GIN | "is the element inside" | tags @> '{java}', JSONB, tsvector, pg_trgm |
| GiST | overlap, distance | tstzrange, PostGIS, EXCLUDE constraint |
| BRIN | a column correlated with physical order | created_at in an append-only log |
About GIN: it's very fast to read, but writes are expensive, since one row can create dozens of index entries. That's why, with fastupdate, new entries go to a pending list first. Keep that in mind on a write-heavy table.
The most practical use of GiST, in my opinion, is preventing overlapping bookings:
CREATE EXTENSION IF NOT EXISTS btree_gist;
ALTER TABLE booking ADD CONSTRAINT no_overlap
EXCLUDE USING gist (room_id WITH =, during WITH &&);
This closes the race condition without any application code.
BRIN stores only the min/max for each block of pages. For a 500 GB log table where a B-tree would be tens of GB, BRIN is a few MB:
CREATE INDEX idx_log_created_brin ON app_log USING brin (created_at);
But it works only if the data really lies on disk in time order. If old rows are updated often and move elsewhere, the min/max ranges widen and BRIN becomes useless.
There is a hash index too, safe with WAL since PG 10, but only for =, and in practice it rarely beats a B-tree.
Sign up to mark studied questions and save your progress.