SQL · Module 11 · Lesson 31 min read

GIN, GiST, BRIN & Hash Indexes

PostgreSQL has several index types, each built for different kinds of data and operators.

TypeBest forTypical operators
B-tree (default)numbers, text, dates, sorting=, <, >, BETWEEN, LIKE 'x%'
GINarrays, JSONB, full-text search, trigram search@>, ?, &&, @@, LIKE '%x%' (with pg_trgm)
GiSTgeometry/maps (PostGIS), ranges, nearest-neighbour&&, <->, overlaps
BRINhuge tables where values follow physical order (logs, time series)<, >, ranges
Hashequality only=

GIN (Generalized Inverted Index) ⭐

Indexes the elements inside a value: each array element, each JSON key, each word.

  • Arrays: CREATE INDEX ON expenses USING gin (tags); → fast tags @> '{social}' (contains)
  • JSONB: CREATE INDEX ON settings USING gin (data); → fast data @> '{"theme":"dark"}'
  • Full-text: USING gin (to_tsvector('english', note))
  • Fuzzy/contains text search: USING gin (title gin_trgm_ops) with the pg_trgm extension → fast ILIKE '%groc%'
  • Slower to build and update than B-tree

GiST

For "overlap" and "distance" questions: map locations ("restaurants within 2 km"), date ranges (no overlapping bookings via an exclusion constraint).

BRIN (Block Range INdex)

Stores only the min/max per block of rows → tiny (kilobytes for gigabytes of data). Works well when rows are inserted in order of the indexed column (e.g. created_at on an append-only log table).

Hash

Equality lookups only. B-tree usually does just as well, so hash indexes are rarely needed.

Choosing

  1. Start with B-tree
  2. Arrays/JSONB/text search → GIN
  3. Geometry/ranges → GiST
  4. Giant append-only tables → BRIN
  5. Always confirm with EXPLAIN ANALYZE

Example

SQL
-- Make tags/notes queries realistic: 50,000 rows
CREATE TABLE notes_demo AS
SELECT g AS id,
       (ARRAY['essential','social','work','travel','monthly'])[1 + g % 5] ||
       CASE WHEN g % 3 = 0 THEN ',personal' ELSE '' END AS tag_text,
       'Expense note number ' || g || CASE WHEN g % 100 = 0 THEN ' groceries' ELSE '' END AS note,
       now() - (g || ' minutes')::interval AS created_at
FROM generate_series(1, 50000) g;
ALTER TABLE notes_demo ADD COLUMN tags TEXT[];
UPDATE notes_demo SET tags = string_to_array(tag_text, ',');
ANALYZE notes_demo;

-- GIN on an array column: "contains" queries
CREATE INDEX idx_notes_tags ON notes_demo USING gin (tags);
EXPLAIN SELECT count(*) FROM notes_demo WHERE tags @> ARRAY['travel', 'personal'];
-- Bitmap Index Scan on idx_notes_tags

-- GIN trigram index: fast ILIKE '%…%' searches
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE INDEX idx_notes_trgm ON notes_demo USING gin (note gin_trgm_ops);
EXPLAIN SELECT id FROM notes_demo WHERE note ILIKE '%grocer%';
-- Bitmap Index Scan on idx_notes_trgm

-- BRIN: tiny index for time-ordered data
CREATE INDEX idx_notes_created_brin ON notes_demo USING brin (created_at);
SELECT pg_size_pretty(pg_relation_size('idx_notes_created_brin')) AS brin_size,
       pg_size_pretty(pg_relation_size('notes_demo'))             AS table_size;
-- a few dozen kB vs several MB

-- GiST + exclusion constraint: no overlapping bookings for the same room
CREATE EXTENSION IF NOT EXISTS btree_gist;
CREATE TABLE room_bookings (
  room   INT,
  during DATERANGE,
  EXCLUDE USING gist (room WITH =, during WITH &&)
);
INSERT INTO room_bookings VALUES (1, '[2026-12-05, 2026-12-08)');
-- INSERT INTO room_bookings VALUES (1, '[2026-12-07, 2026-12-10)');  -- ❌ conflicts (overlap)
INSERT INTO room_bookings VALUES (1, '[2026-12-08, 2026-12-10)');      -- ✅ starts when the other ends

DROP TABLE notes_demo, room_bookings;