Skip to content

Lesson 4 of 13 · 15m

B-tree Is Not Your Only Index

The operator picks the index type: B-tree for ordering and equality, GIN for containment, GiST for overlap and exclusion constraints, BRIN for physically sorted time-series.

CREATE INDEX with no USING clause builds a B-tree. That's the right default — B-trees answer =, <, <=, >, >=, BETWEEN, IN, ORDER BY matching the key order, and LIKE 'prefix%' — but it leaves most people believing "index" and "B-tree" are the same thing. They aren't. Postgres ships six index types, and three of them exist because a sorted B-tree is structurally incapable of answering the operators you actually need.

The wrong model: an index indexes the column

The real unit isn't the column — it's the operator. CREATE INDEX ON events (payload) builds a B-tree on a jsonb column that can accelerate payload = '{...}' comparisons nobody writes. WHERE payload @> '{"kind":"login"}' — containment — will never touch it, no matter how fresh your stats are. The B-tree knows how to compare whole values for ordering. Containment asks "does this document contain these keys," which is an inverted-index question, not a sorting question.

That's what GIN is for. GIN (Generalized Inverted Index) maps each key inside the value to the rows containing it — the same trick Elasticsearch runs on. For jsonb, jsonb_ops indexes every key and value; jsonb_path_ops indexes only the paths and is smaller and faster if all you use is @>. Same story for arrays (tags @> ARRAY['postgres']) and tsvector full-text (to_tsvector('english', body) @@ to_tsquery('...')). If your full-text search does ILIKE '%term%' against a B-tree column, you are running a seq scan with extra steps.

GiST is the third you'll actually deploy: a balanced tree over arbitrary predicates — ranges, geometry, nearest-neighbor. Its killer use isn't even a query accelerator. It's the exclusion constraint:

CREATE EXTENSION btree_gist;  -- stock GiST has no operator class for int =
CREATE TABLE bookings (room int, during tsrange, EXCLUDE USING gist (room WITH =, during WITH &&));

Those two lines make overlapping double-bookings physically unwritable at the database level. The CREATE EXTENSION isn't decoration: stock GiST ships operator classes for ranges and geometry but not scalar =, so room WITH = errors data type integer has no default operator class for access method gist until btree_gist installs one. during WITH && needs nothing extra — range overlap is native GiST territory. No application check, no race window. Trying to do this in a uniqueness constraint or app code is the classic bug — two transactions both check SELECT for conflicts, both see none, both insert.

BRIN: the index for data that's already sorted

Append-only time-series tables — metrics, logs, events — are physically ordered because rows land on disk in created_at order. A B-tree on that column duplicates the ordering that already exists, at gigabytes of index for terabytes of heap. BRIN stores only the min/max value per block range (default 128 pages). It answers WHERE created_at >= now() - interval '1 day' by skipping ranges that can't match, at a few megabytes of index. The requirement is correlation between physical order and the column — pg_statistic's correlation value near 1.0 tells you BRIN will work; near 0 it won't.

And hash indexes: they exist, they're WAL-logged since Postgres 10 (2017), and they're essentially never better than a B-tree for real workloads — B-tree already does = and gives you ranges for free. Know they exist; keep using B-tree.

The honest cost

GIN pays for its power at write time: every insert must post entries to many keys. For write-heavy tables the fastupdate = on storage parameter batches those postings into a pending list, trading a little read slowdown for a lot of write speed. GiST builds slower than B-tree. BRIN loses to B-tree the moment your correlation breaks — a batch UPDATE that rewrites old rows scatters new values across old block ranges and the min/max ranges stop pruning.

What to actually do

  • Match the index type to the operator in your WHERE: =/ranges/ORDER BY → B-tree; @>/@@ on jsonb/array/tsvector → GIN; &&/<</nearest-neighbor → GiST.
  • jsonb columns you only probe with @> get USING gin (payload jsonb_path_ops) — materially smaller than the default jsonb_ops.
  • Overlap invariants belong in EXCLUDE USING gist, not in application code. If two transactions can both pass your check, they eventually will.
  • Before adding a B-tree to an append-only timestamp column, check correlation in pg_stats. Near ±1 → USING brin (created_at) and enjoy a 1000x smaller index.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.