PostgreSQL · Query diagnostics
PostgreSQL EXPLAIN: read the plan before running the query
Separate estimated plans from measured execution, then read row estimates and loops without overlooking side effects.
A slow PostgreSQL query needs evidence, but collecting that evidence can itself create work. Before sharing a plan or running a diagnostic, decide whether you need the planner's estimate or the results of an actual execution.
The short version
What to take away
- EXPLAIN ANALYZE executes the statement, including its normal side effects.
- Compare estimated and actual rows at the same node; account for repeated loops.
- A rollback does not undo sequence advances or remove the cost of the test.
Choose the diagnostic deliberately
Plain EXPLAIN shows the planned operations and estimated costs. Adding ANALYZE executes the statement and reports measurements. An UPDATE still updates rows; a SELECT can still invoke functions with side effects. Discarded query output does not make the execution harmless. Review the statement, environment and expected workload before running it. EXPLAIN command.
The separate ANALYZE command collects table statistics for the planner. It does not produce a measured execution plan for an application query. These similarly named operations answer different questions. ANALYZE command.
Treat execution as a real workload
Prefer an isolated, representative test environment for uncertain or modifying statements. Review triggers and called functions before testing. Decide who can authorize execution and what result would justify a change.
A transaction followed by ROLLBACK can reverse transactional table changes, but it is not a universal safety wrapper. Sequence advances from nextval are not reclaimed after an abort, and setval changes are not rolled back. The query also consumes resources while it runs. Sequence behavior.
Profiling adds overhead. Keep the tested parameters and conditions with the plan, and avoid presenting a single diagnostic run as the application's end-to-end latency.
Read rows, loops and context together
Planner costs use relative units; actual times use milliseconds. Compare estimated and actual output rows at the same node. For repeatedly executed nodes, actual rows and timing are averages per execution, so read loops alongside them.
In a hypothetical node, 10 estimated rows versus 1,000 actual rows means a hundredfold per-execution mismatch. With 20 loops, that node emitted 20,000 rows across its executions. This identifies a useful investigation point, without establishing whether statistics, predicates or another factor caused it.
Follow the plan tree and inspect filters and buffer activity. A sequential scan can be a reasonable choice. Avoid choosing a fix solely from a node's name. Using EXPLAIN.
Sources and next step
The linked guidance is for PostgreSQL 18. Check the documentation for your installed version before using its options.