Skip to Content
Mengty Learns
Architecture

Database Indexing & EXPLAIN ANALYZE

Understand B-tree indexes, composite column order, covering indexes with INCLUDE, write amplification trade-offs, and how to read PostgreSQL EXPLAIN ANALYZE.

explanationintermediateTested with postgresql 19.x (docs)Updated Nov 27, 2026

TL;DR

A B-tree index turns O(N) full-table scans into O(log N) lookups and sorted range scans. Order composite index columns with equality filters first, range filters last, use INCLUDE for covering Index-Only Scans, and verify every query with EXPLAIN (ANALYZE, BUFFERS)—because every unused index slows down writes.

Intent

TL;DR

Design B-tree and covering indexes that match your real query predicates, understand when the planner still chooses a sequential scan, and measure index impact with EXPLAIN (ANALYZE, BUFFERS).

Problem

Without indexes, PostgreSQL must read every 8 KB heap page in a table (Seq Scan) to find matching rows. Developers often react by indexing every column individually—only to discover that write throughput drops, disk usage balloons, and multi-column WHERE + ORDER BY queries still run slowly because column order didn't match the query.

Solution

1. B-tree basics

PostgreSQL's default index (CREATE INDEX ...) is a B-tree (balanced search tree). Keys are stored in sorted order across internal branch pages and leaf pages, which hold pointers (TIDs) to the table's heap tuples. Because keys are sorted, B-trees accelerate =, <, <=, >, >=, BETWEEN, IS NULL, and ORDER BY without an extra sort step.

2. Composite index column order

A multicolumn B-tree index on (org_id, status, created_at) is sorted first by org_id, then status, then created_at:

  • Leftmost prefix rule: Queries filtering on (org_id) or (org_id, status) can seek directly into the tree. A query filtering only on created_at cannot use the tree's top-level ordering.
  • Equality before range: Put = predicates first (org_id, status) and range predicates (created_at >= ...) or ORDER BY columns last. Once a range condition is hit, subsequent columns in the index are no longer contiguous.

3. Covering indexes (INCLUDE)

If a hot query runs SELECT total_cents FROM orders WHERE org_id = $1 AND status = 'paid', a standard index on (org_id, status) still visits the heap table to read total_cents. Adding INCLUDE (total_cents) stores total_cents in the index leaf pages, enabling an Index Only Scan (provided the visibility map marks those pages all-visible).

4. When an index HURTS writes

Every index is a separate data structure on disk and in shared buffers:

  • Every INSERT and DELETE must update all indexes on the table.
  • An UPDATE that modifies an indexed column prevents PostgreSQL HOT (Heap-Only Tuple) updates, forcing new index entries and extra VACUUM work.
  • More indexes mean more WAL (Write-Ahead Log) bytes and higher replication/checkpoint load.

5. Reading EXPLAIN (ANALYZE, BUFFERS)

Always pass ANALYZE and BUFFERS on a non-prod or safe SELECT (wrap mutations in BEGIN; EXPLAIN ANALYZE ...; ROLLBACK;):

  • actual time=0.04..0.12 rows=12 loops=1: Real startup time, total time in ms, actual row count, and loop multiplier.
  • Estimated vs actual rows: Huge mismatches (e.g., rows=1 estimated vs rows=50000 actual) indicate stale statistics (ANALYZE table;).
  • Buffers: shared hit=... read=...: hit means served from PostgreSQL's shared buffer cache; read means fetched from OS cache or disk.

Real-world analogy

▶ Flow: watch it work

Query Planner: Index Scan vs Sequential Scan

Overview of Query Planner: Index Scan vs Sequential Scan. 6 steps.
Overview6 steps in this flow

Press Start or tap any step dot to trace the path.

▸All steps (6)

Code

Example composite covering index and EXPLAIN (ANALYZE, BUFFERS) check in PostgreSQL:

-- Composite index: equality columns (org_id, status) first, range/sort (created_at) last.
-- INCLUDE stores total_cents in leaf pages for Index-Only Scans (not run).
CREATE INDEX CONCURRENTLY idx_orders_org_status_created
  ON orders (org_id, status, created_at DESC)
  INCLUDE (total_cents);

-- Inspect real execution time and buffer hits (not run)
EXPLAIN (ANALYZE, BUFFERS)
SELECT id, total_cents, created_at
FROM orders
WHERE org_id = 42
  AND status = 'paid'
  AND created_at >= NOW() - INTERVAL '7 days'
ORDER BY created_at DESC
LIMIT 20;

When you DON'T need this

  • Tiny lookup tables (< ~1,000 rows): A Seq Scan of one or two 8 KB pages in memory is already faster than traversing a B-tree and jumping to the heap—the planner will ignore your index anyway.
  • Write-heavy append logs rarely queried by filter: Indexing every column on a high-throughput event table can double write I/O for queries nobody runs.
  • Cost / complexity trade-off: Indexes speed up reads dramatically at the cost of extra disk space, RAM buffer pressure, and slower INSERT/UPDATE/DELETE operations.

When to use / when to avoid

When to use
  • Foreign keys, high-cardinality WHERE filters, and hot ORDER BY / cursor pagination columns.
  • Partial indexes (WHERE deleted_at IS NULL) when queries only ever read active rows.
When to avoid
  • Low-cardinality boolean columns on their own (e.g., is_active where 90% of rows are true).
  • Creating overlapping indexes like (a) when you already have (a, b).

How to implement

Capture the slow query

Find top time-consuming queries using pg_stat_statements or slow-query logs.

Run EXPLAIN (ANALYZE, BUFFERS)

Check whether the planner is doing a Seq Scan or reading thousands of buffers for a handful of rows.

Add the smallest matching index concurrently

Use CREATE INDEX CONCURRENTLY in production so writes are not blocked while the index builds, then re-run EXPLAIN (ANALYZE, BUFFERS).

Pros / Cons

Pros
  • Turns full-table scans into sub-millisecond O(log N) lookups and avoids expensive in-memory sorts.
  • Covering indexes (INCLUDE) satisfy hot queries from index leaf pages alone.
Cons
  • Every extra index slows down writes, increases WAL volume, and consumes disk and shared buffers.
  • Stale table statistics can still cause the planner to pick a suboptimal plan.

Relations

Check yourself

Check Yourself

1. You have an index on (org_id, created_at). Which query can use this index for an efficient Index Scan?

2. What does INCLUDE (total_cents) add to a PostgreSQL B-tree index?

Sources