Indexes and Query Performance

Find and fix slow queries with indexes, EXPLAIN ANALYZE, pagination and connection pooling before they hurt users.

Intermediate · about 5 hours · difficulty 4/5

Learn first: Relational Data Modelling in PostgreSQL

Apps feel fast with 100 rows and fall over with 100,000. Placement season traffic spikes are a classic example: every student checks results at the same time.

Indexes

  • An index lets PostgreSQL find rows without scanning the whole table. Primary keys and unique constraints create one automatically.
  • Add indexes on columns you filter, join or sort by often: foreign keys, status, createdAt.
  • Composite indexes follow column order: an index on (opening_id, status) helps queries filtering by both, or by opening_id alone.
  • Indexes speed up reads but slow down writes and use space. Add them for real query patterns.

Measuring

Use EXPLAIN ANALYZE to see whether a query uses an index or does a sequential scan, and how long each step takes. Enable query logging in your ORM during development to spot repeated or N+1 queries.

Other wins

  • Cursor pagination instead of large OFFSET values.
  • Select only the columns you need.
  • Connection pooling (PgBouncer or a provider pooler) so many serverless functions do not exhaust connections.

Pitfalls

  • Adding an index on every column "just in case".
  • Optimising without measuring first.
  • Running heavy reports on the same database at peak time.

You are ready to move on when you can take a slow query on a seeded table of 100,000 applications, read its EXPLAIN ANALYZE output, add the right index and show the before and after timings.

Key concepts

  • B-tree indexes
  • Composite indexes and column order
  • EXPLAIN ANALYZE
  • Spotting N+1 queries
  • Cursor pagination
  • Connection pooling
  • Partial and expression indexes

Mini project

Seed 100,000 fake applications, find the three slowest dashboard queries with EXPLAIN ANALYZE, add appropriate indexes through a migration, and record before and after timings in the README.

Check yourself

You have an index on (status, opening_id) but your query filters only by opening_id. Will the index help, and why?

Free resources