Ira SQL ProIra SQL Pro

Index Types (B-tree, GIN, GiST)

advancedpostgresql
2 min read

What are Index Types?

PostgreSQL supports multiple index types, each optimized for different query patterns and data types. Choosing the right index type can dramatically improve query performance.

Index Types

-- B-tree (default): equality and range queries
CREATE INDEX idx ON students(age);

-- GIN: full-text search, arrays, JSONB
CREATE INDEX idx ON articles USING gin(to_tsvector('english', body));

-- GiST: geometric data, range types, full-text search
CREATE INDEX idx ON events USING gist(event_period);

-- BRIN: large, naturally ordered tables
CREATE INDEX idx ON logs USING brin(created_at);

-- Hash: equality-only lookups
CREATE INDEX idx ON students USING hash(email);

When to Use Each

  • B-tree: Default. Works for =, <, >, <=, >=, BETWEEN, IN, IS NULL.
  • GIN: Full-text search, JSONB containment (@>), array operations (&&, @>).
  • GiST: Geometric/spatial queries, range overlaps (&&), nearest-neighbor.
  • BRIN: Very large append-only tables (logs, time-series) where data is physically ordered.
  • Hash: Pure equality checks (=). Smaller than B-tree but less flexible.

Key Points

  1. B-tree Default — If you do not specify USING, PostgreSQL creates a B-tree.
  2. GIN for JSONB — Essential for fast JSONB containment queries.
  3. GiST for Ranges — Enables exclusion constraints (prevent overlapping bookings).
  4. BRIN is Tiny — BRIN indexes are very small, ideal for huge time-series tables.
  5. Partial Indexes — Any type can be partial: CREATE INDEX ... WHERE condition.

Guided Practice

Solve the challenge below. Use hints when stuck and check your answer for instant feedback.

Practice challengeGuided learning mode

Index Types (B-tree, GIN, GiST) Challenge

Write a query that solve this task: speed up joins on enrollments.student_id.

Expected result

A B-tree index. Joins and WHERE filters on student_id will be faster.

Hidden checks

  • Returned rows and values
  • Output columns and result shape
  • Final database state after the query runs

Lesson guidance

What are Index Types?

Initializing database...Each run starts from fresh sample data.

More Examples

GIN index for full-text search

Index course names for text search.

Initializing database...Each run starts from fresh sample data.

Partial index

Index only active products.

Initializing database...Each run starts from fresh sample data.

Frequently Asked Questions

Which index type should I use by default?
B-tree. It covers the vast majority of use cases. Only switch to GIN, GiST, or BRIN when you have specific data types or query patterns.
Can I have multiple index types on the same table?
Yes. A table can have many indexes of different types on different columns. The planner chooses the best one per query.

Related Topics