NewWork mode: your Claude Code or Codex on work calls, answering from your project's codeSkip to content
Senior0 views

How do you find and optimize a slow SQL query? What do you look at first in EXPLAIN ANALYZE?

Practice

AI answer

First, I reproduce the query with realistic data and measure its execution time and call frequency. Then I inspect the execution plan, for example, EXPLAIN (ANALYZE, BUFFERS) in PostgreSQL. I check the following first:

  • where the actual actual rows and execution time differ most from the planner’s estimates (rows);
  • which nodes take the most time and run many loops;
  • whether the query reads unnecessary rows or pages (Seq Scan, high Buffers values);
  • whether sorts and hash joins are expensive or spill to disk;
  • whether the filtering and join conditions can use the existing indexes.

Next, I check statistics, filter selectivity, join order and types, unnecessary columns, and N+1 calls. I change one factor at a time—for example, rewrite the query or add an appropriate index—then compare the plan and execution time again. EXPLAIN ANALYZE actually executes the query, so I use it cautiously with queries that modify data.