Which PostgreSQL index types exist and when do you use each?
- B-tree (default): equality and range on sortable values,
ORDER BY,LIKE 'abc%'(with the right collation ortext_pattern_ops). Use for most columns. - Hash: equality only; rarely better than B-tree.
- GIN (generalised inverted index): many keys per row:
JSONBcontainment (@>), arrays (&&,@>), full-text search (tsvector), trigram search withpg_trgmforILIKE '%term%'. - GiST: geometric and range types, nearest-neighbour searches, exclusion constraints (no overlapping bookings), PostGIS.
- SP-GiST: space-partitioned data (quad-trees, IP ranges).
- BRIN (block range index): tiny index for huge, naturally ordered tables (time-series appended by time): stores min/max per block range.
- pgvector HNSW / IVFFlat: approximate nearest-neighbour search on embeddings.
Modifiers
- Partial:
WHERE deleted_at IS NULLindexes only live rows. - Expression:
ON users (lower(email)). - Covering:
INCLUDE (amount)enables index-only scans. - Concurrent builds:
CREATE INDEX CONCURRENTLYavoids blocking writes on a live system (cannot run in a transaction; check for invalid indexes if it fails).
Example
sql
-- Case-insensitive unique email
CREATE UNIQUE INDEX CONCURRENTLY uq_users_email ON users (lower(email));
-- JSONB containment queries
CREATE INDEX idx_products_attrs ON products USING GIN (attributes jsonb_path_ops);
SELECT * FROM products WHERE attributes @> '{"color": "red"}';
-- Fuzzy search on names
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE INDEX idx_customers_name_trgm ON customers USING GIN (name gin_trgm_ops);
SELECT * FROM customers WHERE name ILIKE '%sharma%';
-- No double booking of a room (exclusion constraint with GiST)
CREATE EXTENSION IF NOT EXISTS btree_gist;
ALTER TABLE bookings ADD CONSTRAINT no_overlap
EXCLUDE USING GIST (room_id WITH =, tstzrange(starts_at, ends_at) WITH &&);
-- Huge append-only log table
CREATE INDEX idx_logs_created_brin ON logs USING BRIN (created_at);Follow-up questions interviewers ask
Try answering each one before you open it.
How do you find unused indexes?
Query pg_stat_user_indexes for indexes with idx_scan = 0 over a long period (after checking replicas too, since statistics are per server), excluding those that enforce primary keys or unique constraints. Dropping them speeds up writes and vacuum.