Indexes and Query Performance
Make queries fast with the right indexes and learn to read query plans and profile slow queries.
Intermediate · about 8 hours · difficulty 4/5
Learn first: Writing SQL Queries, ORMs and Query Builders
An index is a separate data structure (usually a B-tree) that lets the database find rows without scanning the whole table, much like a book's index. Indexes make reads faster and writes slightly slower, and they use disk and memory.
Choosing indexes
- Index columns used in
WHERE,JOINandORDER BYon large tables. - Composite indexes follow the leftmost-prefix rule: an index on
(user_id, created_at)helpsWHERE user_id = ?andWHERE user_id = ? ORDER BY created_at, but notWHERE created_at > ?alone. - Unique indexes enforce uniqueness; partial indexes (
WHERE deleted_at IS NULL) keep indexes small; covering indexes can answer a query without touching the table. - Specialized types: GIN for JSONB and full-text, BRIN for huge append-only tables.
Reading plans
EXPLAIN ANALYZE runs a query and shows the plan: sequential scans, index scans, join strategies, estimated versus actual rows. A big gap between estimated and actual rows often means stale statistics.
Finding slow queries
Enable pg_stat_statements (or your engine's slow query log) to see which queries consume the most total time. Optimize the top few; that is where the wins are.
Pitfalls
- Wrapping an indexed column in a function (
WHERE lower(email) = ...) so the index cannot be used, unless you create an expression index. - Adding an index for every column. Measure first.
You are ready to move on when you can take a slow query, read its plan, add the right index and show the before and after timings.
Key concepts
- B-tree indexes
- Composite index column order
- Unique, partial and covering indexes
- GIN, GiST and BRIN
- EXPLAIN ANALYZE
- pg_stat_statements and slow query logs
- Table statistics and VACUUM
Mini project
Generate a table with 5 million rows, write three realistic slow queries, and bring each under 10 ms with appropriate indexes, documenting EXPLAIN ANALYZE output before and after.
Check yourself
You have an index on (status, created_at). Which of these can use it well: WHERE status = 'paid', WHERE created_at > now() - interval '1 day', or both?
Free resources
- Use The Index, Luke (Markus Winand)
- PostgreSQL: Using EXPLAIN (PostgreSQL)
- PostgreSQL: Indexes (PostgreSQL)