← Back to SQL, page 18

sql-0342 · Medium mid

An API endpoint that lists orders became slow after the table grew. Walk through how you would investigate.

Capture the exact slow SQL and its parameters, then run EXPLAIN (ANALYZE in PostgreSQL) to see whether it scans the whole table, sorts large sets or loops badly. Compare estimated and actual row counts, add or adjust an index that matches the filter and sort, and confirm the plan and timing improve. Also check that the endpoint is not issuing one query per row.

Full answer

A practical order of work:

  1. Find the query. Use slow query logs or pg_stat_statements to see the statement, how often it runs and its average time. Endpoint slowness is sometimes a hundred fast queries, not one slow one.
  2. Reproduce with real parameters. A plan for customer_id = 5 can differ from one for a customer with a million orders.
  3. Read the plan. Look for sequential scans on large tables, sorts spilling to disk, nested loops over many rows and big gaps between estimated and actual rows.
  4. Fix the cause. Typical fixes are a composite index matching WHERE customer_id = ? ORDER BY placed_at DESC, keyset pagination instead of large OFFSETs, selecting fewer columns, or refreshing statistics with ANALYZE.
  5. Verify. Rerun EXPLAIN ANALYZE, then watch the production metric after release.

Also check for lock waits, because a fast query blocked by a long transaction looks slow from the outside.

Key points

  • Measure before changing anything
  • Use real parameters when reading plans
  • Compare estimated and actual rows
  • Match indexes to filter plus sort
  • Check for lock waits and N+1 patterns

Common mistakes

  • Adding indexes at random
  • Testing plans on a tiny development database

Follow-ups

  • What does a large estimate error suggest?
  • How does OFFSET pagination slow down?

Tips

  • Give the steps in order