Indexes are the most important tool for query optimization. A well-designed index can turn a query from seconds to milliseconds. Here's how to use them effectively.
How Indexes Work#
Without index (table scan):
Query: SELECT * FROM users WHERE email = 'john@example.com'
Table: 1,000,000 rows
Operation: Scan every row → 1,000,000 comparisons
Time: O(n)
With index (index lookup):
B-tree index on email column
Operation: Tree traversal → ~20 comparisons
Time: O(log n)
Index Types#
B-Tree (Default)#
Hash Index#
GIN (Generalized Inverted Index)#
GiST (Generalized Search Tree)#
Composite Indexes#
Column Order Matters#
Design Principles#
Covering Indexes (Index-Only Scans)#
Partial Indexes#
Expression Indexes#
Analyzing Index Usage#
EXPLAIN ANALYZE#
Finding Unused Indexes#
Finding Missing Indexes#
Common Patterns#
Foreign Key Indexes#
Pagination#
Soft Deletes#
Anti-Patterns#
Over-Indexing#
Low Selectivity Indexes#
Functions Preventing Index Use#
Maintenance#
Monitoring Index Bloat#
Rebuilding Indexes#
Conclusion#
Indexes are essential for query performance but come with trade-offs. Start with indexes on foreign keys and frequently-queried columns. Use EXPLAIN ANALYZE to verify index usage. Monitor for unused indexes and remove them.
Remember: the best index is one that helps your actual queries. Profile first, then optimize.