Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 127/ 160
07. Indexing, Query Optimization & Performance Tuning

Specialized Indexes (Hash, GIN, GiST, BRIN for Time-Series)

Pick Hash, GIN, GiST, or BRIN when B-Trees are the wrong tool.

AdvancedGIN / GiST · Hash3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

Nearest stores with GiST (PostGIS)Query example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1CREATE INDEX ON stores USING gist (location);23SELECT4  name5FROM6  stores7ORDER BY8  location <-> ST_MakePoint (73.85, 18.52)::geography9LIMIT10  5;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/10
3OutputInspect the representative rows, affected-row count, plan, or command status.
Nearest sample stores3 sample rows
Nearest sample stores
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.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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.

A tiny index for a huge logQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1CREATE INDEX events_created_brin ON events USING brin (created_at);
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/1
query.sql
1SELECT2  correlation3FROM4  pg_stats5WHERE6  tablename = 'events'7  AND attname = 'created_at';
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/7
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative column correlation1 sample row
Representative column correlation
correlation
0.997

Note: The statistic is illustrative and available after ANALYZE; actual correlation depends on stored order and PostgreSQL statistics.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

then check

is close to 1.

Key takeaway: BRIN for huge, naturally ordered data; B-tree over hash in most cases.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Query

Look at the operator

Identify the operator in the WHERE or ORDER BY: equality and ranges, containment, overlap, distance, or a big time range.

Focus at this step

=, < · @> · && · <->

What to watch at this step
Operator
decides the type
Tip: use ← → to move between steps

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

GIN
Best for: JSONB, arrays, full-text, trigram search

Strengths: Very fast "contains" lookups.

Watch out: Larger and slower to update.

GiST
Best for: Ranges, geometry, nearest-neighbour, exclusion constraints

Strengths: Handles overlap and distance queries B-trees can't.

Watch out: Often slower than GIN for pure containment.

BRIN
Best for: Billions of rows ordered by time or id

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"?
Interview tip: Frame index types by the question they answer (compare, contains, overlaps or near, huge ordered range), then give one example each. That structure is easy to follow and shows real depth.

Knowledge check

Loading quiz

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.

Open SQL Practice →SQL interview Q&A
Previous topic
Partial Indexes (Filtered Indexes) & Expression / Functional Indexes
Next topic
Index Scan vs Index-Only Scan vs Bitmap Scan vs Sequential Scan