Engineering PostgreSQL Databases Performance

PostgreSQL Indexing Strategies: From Slow Queries to Lightning Fast

10 min readWANOVA

A query taking 8 seconds on a 2-million-row table becomes 12 milliseconds after one correct index. This is not an exaggeration — this is the actual effect of a B-tree index replacing a sequential scan that PostgreSQL was forced to perform without it. Database indexing is the single highest-leverage performance optimization available to most applications, and yet it is routinely under-invested in. This guide takes you from indexing fundamentals to the advanced strategies used in real production platforms serving millions of rows, including composite indexes, partial indexes, covering indexes, and how to read execution plans to verify your indexes are being used correctly.

How Indexes Work: A Concept You Cannot Skip

Without an index, PostgreSQL performs a Sequential Scan: it reads every row in the table from start to finish looking for matches. On a table with 2 million rows, this is catastrophically slow for any query filtering on a non-indexed column. An index is a separate, sorted data structure that enables Binary Search — reducing the number of comparisons from N to log₂(N). The tradeoff is write overhead: every INSERT, UPDATE, and DELETE must also update all indexes on the affected columns.

  • B-tree: the default, excellent for =, <, >, BETWEEN, ORDER BY
  • Hash: for = only, slightly faster than B-tree for pure equality
  • GiST/GIN: for geographic data, Full-text search, Arrays
  • Indexes slow writes: every INSERT/UPDATE updates all indexes — don't index what you don't read
  • Index selectivity: high-cardinality columns (user_id, email) benefit most from indexes
  • Null handling: B-tree indexes include NULL values — use WHERE col IS NOT NULL for partial exclusion
  • Index size monitoring: large indexes that exceed working memory slow down query planning
→ Rule: an index on a column read once per 100 writes = worthwhile. The reverse hurts more than it helps.

Index Types and When to Use Each

Index TypeBest ForExample
B-treeNormal queries (=, <, >)WHERE user_id = 5
PartialOnly part of the tableWHERE status = 'active'
CompositeMulti-column queriesWHERE tenant_id = 1 AND status = 'active'
GINFull-text search, ArraysWHERE tags @> ARRAY['react']
BRINLarge tables with natural orderingWHERE created_at BETWEEN...

Composite Indexes: Column Order Matters Enormously

A composite index on (tenant_id, created_at) is fundamentally different from one on (created_at, tenant_id). The first efficiently serves queries filtering by tenant_id and ordering by created_at — the most common pattern in multi-tenant SaaS. The second serves queries ordering by created_at across all tenants. Getting column order wrong in a composite index means the index is not used at all for the most frequent queries, which is worse than having a correctly ordered single-column index.

  • Put the highest cardinality column first
  • Correct example: (user_id, created_at) for query: WHERE user_id=X ORDER BY created_at DESC
  • Covering index: add SELECT columns to the index — PostgreSQL never touches the table
  • CREATE INDEX ON enrollments (user_id, course_id) INCLUDE (completed_at, score);
  • Covering index query with 0 heap accesses = fastest possible
  • Prefix matching: a composite index (a, b, c) can serve queries on (a), (a, b), (a, b, c) — not (b) alone
  • Index-only scans: when all queried columns are in the index, PostgreSQL skips the heap entirely
  • Multi-tenant pattern: always include tenant_id as first column in composite indexes

Partial Indexes: Index Only the Data You Actually Query

If 95% of your queries filter by WHERE status = 'active', there is no value in indexing inactive, deleted, or archived records. A partial index that covers only the active rows is dramatically smaller, faster to update, and fits entirely in the PostgreSQL buffer cache — making it faster to search than a full index on the same column.

  • CREATE INDEX ON orders (created_at) WHERE status = 'pending';
  • This index is much smaller and covers exactly the most frequent queries
  • Partial unique index: CREATE UNIQUE INDEX ON users (email) WHERE deleted_at IS NULL;
  • Partial indexes update faster because most writes don't affect them
  • Soft-delete pattern: (email) WHERE deleted_at IS NULL enforces uniqueness only for active records
  • Payment indexes: (created_at) WHERE status IN ('pending', 'processing') covers the actionable set
  • Estimate savings: pg_relation_size('index_name') shows actual index size — compare full vs partial

Reading Execution Plans: EXPLAIN ANALYZE

EXPLAIN ANALYZE is the primary diagnostic tool for understanding why a query is slow and verifying that your indexes are being used. Every performance optimization should start and end with EXPLAIN ANALYZE — start to understand the problem, end to verify the fix worked. Reading execution plans is a skill worth investing in: a 30-minute study of execution plan output can reveal optimizations that save hours of investigation.

  • EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) SELECT ...;
  • Look for: Seq Scan on large tables = missing index
  • Nested Loop with large table = wrong query structure
  • Rows=10000 actual=3 = stale database statistics → ANALYZE;
  • pgMustard tool: analyzes execution plans and gives you English recommendations
  • Bitmap Heap Scan: PostgreSQL uses index to collect row pointers, then fetches in heap order — normal for range queries
  • Cost units: arbitrary units showing relative expense — actual time is what matters for optimization
  • EXPLAIN ANALYZE on production: use pg_stat_statements to identify slow queries without manual EXPLAIN

Common Indexing Mistakes That Hurt Performance

Most indexing mistakes fall into two categories: under-indexing (missing indexes on columns used in WHERE and JOIN) and over-indexing (indexes that are never used but slow down every write). Both are fixable once you have the right diagnostic data. The pg_stat_user_indexes view shows index usage statistics — any index with zero scans after weeks of production traffic should be dropped.

  • Indexing every column: slows writes significantly without benefit
  • Not indexing Foreign Keys: every JOIN without an index = Seq Scan
  • Ignoring Index Bloat: indexes grow over time — REINDEX CONCURRENTLY periodically
  • Forgetting CONCURRENTLY: CREATE INDEX locks the table without this keyword — catastrophic in production
  • Index on column used in LIKE '%text%': doesn't work — use Full-text search
  • Function on indexed column: WHERE LOWER(email) = 'x' ignores an index on email — use expression indexes
  • Implicit type casting: WHERE user_id = '5' (string literal) on an integer column prevents index use
  • Unused indexes: query pg_stat_user_indexes monthly and drop indexes with idx_scan = 0

Index Maintenance in Production

Indexes require ongoing maintenance to remain effective. Index bloat, stale statistics, and lock management during index creation are all real production concerns that teams often ignore until they cause an incident. A quarterly index maintenance routine catches these issues before they become problems.

  • pg_stat_user_indexes: identify unused indexes for removal each quarter
  • pg_stat_user_tables: check n_live_tup vs n_dead_tup — high dead tuples signal need for VACUUM
  • REINDEX CONCURRENTLY: rebuild bloated indexes without locking the table in production
  • ANALYZE: update statistics after large data loads or significant table changes
  • autovacuum tuning: ensure autovacuum runs frequently enough on high-write tables
  • Index bloat query: pg_bloat_check extension gives precise index bloat percentage per index
  • pg_trgm extension: enables fast LIKE queries with trigram indexes — better than full-text for short patterns

Real Case Study

Nur Al Huda Academy — Full LMS Platform

How we built an educational platform serving thousands of students from scratch — architecture, challenges, and real results.

Read the Case Study

Free 30-minute consultation

Get an initial concept for your platform.

شعار وانوفا WANOVA

Built for the future. Premium digital platforms and cinematic software solutions.

Quick Links

© 2026 WANOVA. All rights reserved.