Proper indexing can transform query performance from seconds to milliseconds. This guide covers indexing strategies, types, and practical patterns for PostgreSQL and other databases.
How Indexes Work
Without an index, the database performs a sequential scan:
With an index, the database uses a B-tree structure for O(log n) lookups:
Index Types
B-Tree Index (Default)
Best for equality and range queries:
GIN Index
For arrays, JSONB, and full-text search:
Partial Indexes
Index only the rows you need:
Covering Indexes
Include additional columns to avoid table lookups:
Composite Indexes
Order matters for multi-column indexes:
Analyzing Index Usage
Common Anti-Patterns
- Over-indexing: Too many indexes slow writes
- Low-selectivity columns: Boolean indexes rarely help
- Wrong column order: Composite index order matters
- Functions on columns:
LOWER(email)needs expression index
Conclusion
Effective indexing requires understanding your query patterns. Start by analyzing slow queries with EXPLAIN ANALYZE, create targeted indexes, and monitor usage.