How do you find and optimize a slow SQL query? What do you look at first in EXPLAIN ANALYZE?
Asked at
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 rowsand 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, highBuffersvalues); - 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.
Also asked at ГК МЕДСИ
- [name] asked: How does memory management work in Python (garbage collector, reference counting)?
- What is the difference between TaskGroup and the gather function in the asyncio library in Python?
- What solutions did you implement to work around ChatGPT being unavailable from Russian IP addresses?
- How do you scale web application workers (for example, in FastAPI or Django), and which server did you use on your project?
- What blocks the event loop, how do you detect it in production, and what should you do about blocking code?
Similar questions
- Have you used EXPLAIN?
- If the problem turns out to be on the database side and a SELECT query is taking a long time, what would you do? Which columns are indexes usually created on?
- Why can an OFFSET of a million rows be slow even when there is an index?
- Why is it bad to have too many indexes in a database table?
- What join algorithms are used in PostgreSQL? What is the difference between Nested Loop, Hash Join, and Merge Join, and when is each preferable?