Ankit KanojiyaAdvanced

Evergreen guide by Ankit Kanojiya · Advanced · Databases

Database Indexing Deep Dive: How Indexes Really Work

An explanation of B-tree and other index types, how the planner uses them, and the trade-offs of adding indexes.

Indexes are the single most effective tool for speeding up reads, yet they are easy to misuse. Understanding how they are structured and when the planner chooses them turns indexing from guesswork into engineering.

The B-tree, the default for a reason

Most relational indexes are balanced B-trees. Keys are kept sorted across a shallow tree of pages, so a lookup touches only a handful of pages regardless of table size. Because the tree stays balanced, point lookups and range scans both run in logarithmic time.

B-trees serve equality, range, sorting, and prefix queries. A single index on (a, b, c) can satisfy filters on a, on a and b, or all three, but it cannot efficiently filter on b alone. This left-to-right rule is the most important thing to internalize about composite indexes.

create index idx_orders_customer_date
  on orders (customer_id, created_at);

-- Uses the index efficiently:
select * from orders
where customer_id = 42 and created_at >= date '2026-01-01';

Other index types

B-trees are not the only option:

  • Hash indexes handle only equality but can be smaller and faster for that case.
  • GIN indexes accelerate containment queries on arrays, jsonb, and full-text search.
  • GiST indexes support geometric and range overlap queries.
  • BRIN indexes store per-block summaries, giving tiny indexes for naturally ordered data like append-only timestamps.

Choosing the right type matters as much as choosing the right columns. A GIN index on a jsonb column can transform a sequential scan into an instant lookup.

Covering indexes and index-only scans

If an index contains every column a query needs, the engine can answer from the index alone without visiting the table heap. PostgreSQL supports this with INCLUDE columns.

create index idx_orders_covering
  on orders (customer_id) include (status, total);

A query selecting only status and total filtered by customer_id can now run as an index-only scan, avoiding heap fetches entirely.

How the planner decides

Having an index does not guarantee it is used. The query planner estimates the cost of each access path from table statistics and picks the cheapest. If a filter matches a large fraction of rows, a sequential scan can genuinely be faster than random index lookups, so the planner skips the index on purpose.

Use EXPLAIN ANALYZE to see the real plan and compare estimated to actual rows:

explain analyze
select * from orders where status = 'pending';

Large gaps between estimated and actual row counts usually mean stale statistics. Running ANALYZE refreshes them.

The cost of every index

Indexes are not free. Each one:

  • Consumes storage, sometimes as much as the table itself.
  • Slows down every insert, update, and delete, since the index must be maintained.
  • Can be updated on write even when the indexed column did not change, depending on the engine.

The practical guidance is to index for the queries that actually run, measure, and remove indexes that the planner never picks. Monitoring unused indexes is as valuable as adding new ones.

Common pitfalls

  • Wrapping an indexed column in a function, such as where lower(email) = ..., prevents index use unless an expression index exists.
  • Leading wildcards like like '%term' cannot use a standard B-tree.
  • Low-cardinality columns, such as a boolean flag, rarely benefit from a plain index; a partial index is often better.
create index idx_orders_open
  on orders (created_at)
  where status = 'open';

A partial index stays small because it covers only the rows that matter, which keeps both lookups and writes cheap.

Takeaways

Index the columns your real queries filter and sort on, prefer composite indexes ordered by selectivity and usage, and verify every choice with EXPLAIN ANALYZE against representative data. Indexing is an ongoing process of measuring and pruning, not a one-time setup.