Specialized Indexes (Hash, GIN, GiST, BRIN for Time-Series)
Pick Hash, GIN, GiST, or BRIN when B-Trees are the wrong tool.
In plain words
Different index types answer different kinds of questions; pick the one that fits how you search.
Think of it like…
Different catalogues for different questions: an alphabetical card index (B-tree), a word index at the back of a book (GIN), a map with zones for "what's near here" (GiST), and shelf labels saying "this shelf holds March to April" (BRIN).
Where you’ve seen it
An events table with 3 billion rows appended in time order: a B-tree on created_at would be over 60 GB; a BRIN index is a few megabytes and still lets WHERE created_at >= now() - interval '1 day' skip almost every block. The same app uses GIN on a JSONB attributes column and GiST for booking date ranges.
Words you’ll hear
- B-tree
- Default: equality, ranges, sorting, prefix LIKE.
- GIN
- Inverted index for contains / exists queries: jsonb @>, array @>, full-text, trigram.
- GiST / SP-GiST
- Spatial, range overlap, nearest-neighbour (ORDER BY … <->), exclusion constraints.
- BRIN
- Block-range summaries; tiny, effective when values correlate with physical row order.
Visual diagram
Theory & example queries
GIN and GiST
GIN maps each element (a JSON key or value, an array item, a word, a trigram) to the rows that contain it, like a book's index. It accelerates attributes @> '{"brand": "Acme"}', tags @> ARRAY['sale'], search @@ to_tsquery(…) and, with pg_trgm, name ILIKE '%term%'. Reads are fast; writes cost more because one row can add many index entries (the fastupdate setting buffers them).
GiST is a framework for tree indexes over shapes and ranges: PostGIS geometries, range types (&& overlaps, @> contains), and nearest-neighbour ordering (ORDER BY location <-> point LIMIT 10). It also powers exclusion constraints such as "no two bookings for the same room may overlap". SP-GiST covers space-partitioned data like IP ranges and quadtrees.
CREATE INDEX ON stores USING gist (location);SELECT nameFROM storesORDER BY location <-> ST_MakePoint (73.85, 18.52)::geographyLIMIT 5;PostgreSQL is the lesson baseline unless noted otherwise.
Identify the table or database object the statement will modify.
Nearest sample stores3 sample rows
| name |
|---|
| Deccan Store |
| Pune Camp Store |
| Kothrud Store |
Note: Distances and ordering depend on the stores and the PostGIS/geography calculation; the table shows the first three of up to five names.
Key takeaway: GIN for "contains", GiST for "overlaps / near".
BRIN and hash
BRIN stores, for each range of table blocks (128 pages by default), the minimum and maximum value. A query skips every block range whose summary can't match. That only works when the column's values follow the physical order of rows, as with timestamps in append-only logs or sequential ids, so check correlation in pg_stats (close to 1 or -1 is good). On randomly ordered data, BRIN is useless.
Hash indexes support only equality, and in PostgreSQL 10+ they're crash-safe, but a B-tree is usually as fast and far more versatile, so hash indexes are rarely chosen. Whatever the type, confirm with EXPLAIN that the planner uses it for the queries you care about.
CREATE INDEX events_created_brin ON events USING brin (created_at);PostgreSQL is the lesson baseline unless noted otherwise.
Identify the table or database object the statement will modify.
SELECT correlationFROM pg_statsWHERE tablename = 'events' AND attname = 'created_at';PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Representative column correlation1 sample row
| correlation |
|---|
| 0.997 |
Note: The statistic is illustrative and available after ANALYZE; actual correlation depends on stored order and PostgreSQL statistics.
then check
is close to 1.
Key takeaway: BRIN for huge, naturally ordered data; B-tree over hash in most cases.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Look at the operator
Identify the operator in the WHERE or ORDER BY: equality and ranges, containment, overlap, distance, or a big time range.
=, < · @> · && · <->
When to use it & trade-offs
What it is
Beyond the default B-tree, PostgreSQL offers index types for other kinds of questions. GIN is an inverted index for "which rows contain this element?" (JSONB keys, arrays, full-text words, trigrams). GiST handles geometry, ranges and nearest-neighbour searches. BRIN stores tiny per-block summaries for huge tables whose values follow the physical order, like timestamps in an append-only log. Hash supports equality only.
Why it matters: A B-tree can't answer "documents containing this word", "bookings overlapping this period" or "the nearest stores". Picking the index type that matches the operator turns those queries from full scans into fast lookups, and BRIN can index a terabyte-sized log in a few megabytes.
When to reach for it
- GIN on JSONB attributes, tags arrays and search columns
- GiST on booking ranges and locations
- BRIN on large append-only event and log tables
When to avoid or be careful
- B-tree indexes on JSONB columns expecting @> to use them
- BRIN on columns whose values are randomly ordered on disk
- Hash indexes where a B-tree would do the same job
GIN vs GiST vs BRIN
Strengths: Very fast "contains" lookups.
Watch out: Larger and slower to update.
Strengths: Handles overlap and distance queries B-trees can't.
Watch out: Often slower than GIN for pure containment.
Strengths: Tiny and cheap to maintain.
Watch out: Only useful when values follow physical order; coarse filtering.
Interview signals & numbers to know
When this topic comes up
- “Filter on JSON fields is slow”
- “Find the nearest stores”
- “Index a 2 TB log table”
- Overlapping bookings
- Index type choice
Benchmarks & rules of thumb
- 128 pages
- default BRIN block range
- PostgreSQL 10
- hash indexes became crash-safe
- ≈ 1
- good correlation for BRIN
Common mistakes & follow-ups
Common interview mistakes
- Creating a B-tree on a jsonb column and wondering why containment queries still scan.
- Using BRIN on a table that's frequently updated in random order, so every block range covers all values.
- Adding GIN indexes to a write-heavy table without measuring the slowdown on inserts.
Likely interviewer follow-ups
- Which index would you use for a JSONB containment query?
- When is a BRIN index a good choice?
- How would you speed up "find the 10 nearest restaurants"?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Specialized Indexes (Hash, GIN, GiST, BRIN for Time-Series) with hands-on SQL practice and interview Q&A.