Indexes are the single most effective tool for speeding up database reads, and the most common reason a query that was fast in development becomes slow in production. This guide covers what application developers need to know, using PostgreSQL examples that apply broadly to MySQL too.

What an index is

A B-tree index is a sorted structure that maps column values to row locations. Instead of reading every row (a sequential scan), the database walks the tree to find matching rows quickly. Lookups go from proportional to the table size to roughly proportional to the tree depth.

When you need one

Index columns used in:

  • WHERE filters on large tables (WHERE customer_id = ?).
  • JOIN conditions (foreign keys are the classic missing index).
  • ORDER BY with LIMIT (newest orders first).
  • Uniqueness constraints (which create indexes automatically).

Composite index order matters

For WHERE customer_id = ? AND status = ? ORDER BY created_at DESC LIMIT 20, the right index is:

CREATE INDEX CONCURRENTLY idx_orders_customer_status_created
  ON orders (customer_id, status, created_at DESC);

Rule of thumb: equality columns first, then the sort column, then range conditions. An index on (created_at, customer_id) would not help this query much.

Reading EXPLAIN

EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders WHERE customer_id = 812 AND status = 'open' ORDER BY created_at DESC LIMIT 20;
You seeMeaning
Seq Scan on ordersNo usable index, reading the whole table
Index Scan using idx_...Using the index, then fetching rows
Index Only ScanAll needed columns are in the index; no table access
Bitmap Heap ScanCombining index results, then reading pages
Sort (external merge)Sorting more than fits in memory
rows=10 vs actual rows=100000Bad estimate; run ANALYZE

Covering indexes

If a frequent query needs only a few columns, include them so the database can answer from the index alone:

CREATE INDEX idx_orders_customer_cover ON orders (customer_id) INCLUDE (status, total);

When indexes hurt

  • Every write updates every index: tables with many indexes have slower inserts and updates.
  • Unused indexes cost storage and memory for nothing; check usage statistics (pg_stat_user_indexes) and drop the unused ones.
  • Low-selectivity columns (a boolean where 90% of rows are true) rarely benefit; partial indexes on the rare value do (WHERE is_archived = false).
  • Functions on columns prevent index use: WHERE lower(email) = ? needs an expression index on lower(email).

Adding indexes safely in production

Plain CREATE INDEX locks writes on the table for the duration. In PostgreSQL use CREATE INDEX CONCURRENTLY (slower, but does not block writes), and check for an invalid index if it fails. In MySQL, InnoDB supports online index creation for most cases. Schedule large index builds outside peak hours and watch replication lag. See zero-downtime database migrations.

Finding which queries need indexes

Start from user impact: the slowest endpoints in APM, then the slow database spans inside their traces, then EXPLAIN. Database-side, pg_stat_statements ranks queries by total time. The full workflow is in how to find slow database queries.

Verify the result

After adding an index, compare the endpoint's p95 and the query's mean time before and after. VitalRix APM shows database call volume, p95 and slow calls per statement over time, so the improvement (or lack of one) is visible the same day.

A worked example

An orders page loaded a customer's 20 most recent orders and took 1.8 seconds for large customers. EXPLAIN showed a sequential scan over 4 million rows filtered by customer_id and then sorted by created_at. Adding an index on (customer_id, created_at DESC) turned it into an index scan reading 20 rows, and the query dropped to 3 ms. The page's p95 fell from 1.8 s to 160 ms. Inserts into orders slowed by a fraction of a millisecond, which nobody noticed.

Index maintenance

  • Bloat: in PostgreSQL, heavily updated tables can bloat indexes; REINDEX CONCURRENTLY rebuilds them without blocking writes.
  • Statistics: autovacuum's analyze keeps planner statistics current; after large data loads, run ANALYZE yourself.
  • Duplicates: an index on (a) is usually redundant if (a, b) exists.

A review checklist for new queries

  1. Which columns does it filter, join and sort on?
  2. Is there an index that starts with the equality columns?
  3. Does EXPLAIN on production-sized data use it?
  4. How many rows does it read compared with rows returned?
  5. How often will it run, and how often will the table be written?

See PostgreSQL monitoring for keeping an eye on index usage over time.

Should I index every foreign key?

Usually yes for columns used in joins or cascaded deletes on large tables. Unindexed foreign keys are a common cause of slow deletes and lock contention.

How many indexes is too many?

There is no fixed number. If writes are slow and some indexes are unused, drop the unused ones first.

Why is my index not used?

The planner thinks a scan is cheaper (small table, low selectivity, stale statistics), the query applies a function to the column, or the column order does not match the query.

Try VitalRix free

Uptime monitoring, APM, logs, real user monitoring and status pages in one place. No credit card needed.