Slow Query Diagnosis

pg_stat_statements, slow query log, EXPLAIN ANALYZE, missing indexes, N+1 queries, and query rewrites.

Overview

Overview

Slow queries are one of the most common causes of production performance degradation. They fall into a handful of categories, and each one leaves a different fingerprint in the execution plan or the application logs.

The work always runs in the same four moves. Find the slow query with pg_stat_statements or the slow log. Explain it with EXPLAIN ANALYZE. Read the red flags in the plan. Then fix it with an index, a rewrite, eager loading or ANALYZE.

Key concepts

  • pg_stat_statements
  • EXPLAIN (ANALYZE, BUFFERS)
  • N+1 query
  • Covering index
  • log_min_duration_statement

Interview questions

  • How do you find and fix an N+1 query problem in a production application?
  • A query that used to take 10ms now takes 30 seconds. Nothing changed in the code. What happened?

Sign up free to read the full topic

More Troubleshooting topics

Start free on Cariara · Coding problems · System design studio