Reading EXPLAIN ANALYZE to fix slow PostgreSQL queries

A slow PostgreSQL query usually shows its cause in the plan: where estimated and actual rows diverge, which join strategy runs, and where time and buffer reads go. This page explains how to read those signals and which fixes follow.

On this page

Why EXPLAIN ANALYZE should come before any slow query fix

When a query is slow in production, the pressure to act is strong. Someone proposes a larger shared_buffers, another person suggests an index on every filtered column, and a change goes out before anyone has confirmed where the time actually goes. EXPLAIN ANALYZE should come first. It executes the statement and reports the plan the planner actually used, along with the row counts at each step, the buffers touched and the time spent in each node. Without that output, a team is choosing a fix from guesswork, and a settings change or new index can easily move the problem somewhere else.

Teams usually need this skill at two points. The first is after pg_stat_statements has ranked a query as expensive, so the team knows which statement matters but not why it is slow. The second is during a release review, when a new or changed query needs to be checked before it reaches production data volumes. In both cases, plain EXPLAIN shows only the estimated plan, which can differ sharply from reality when statistics are stale or data is skewed. Ask the database owner whether the environment holds production-sized data, because a plan from a small test database may not match production.

The write-safety point matters before anyone runs the command. EXPLAIN ANALYZE really executes the statement, so an INSERT, UPDATE, DELETE or a function with side effects will change data. Wrap data-modifying statements in a transaction and roll it back, and confirm with the application owner that running the query against live data is acceptable at that hour. Also check statement timeouts and the load the execution will add. Agree these checks in the change record before anyone runs the command in production.

Reading BUFFERS and timing to locate where the time goes

Each node in an EXPLAIN ANALYZE plan reports an actual total time, and that figure is inclusive of its children. A node's own work is roughly its total time minus the total time of its child nodes, so the top node always shows the largest number and says little on its own. Start by reading from the bottom of the tree upward and find the node whose exclusive time is largest. Loops matter too: a node that runs once per outer row reports a per-loop average, so the total cost is the average multiplied by the loop count. Check the following:

  • Inclusive versus exclusive time: subtract child totals from each parent to find the node doing the work itself.
  • Loop multiplication: multiply actual time and rows by loops before comparing nodes inside a nested loop.
  • Sort and hash spills: a sort or hash node that reports disk usage in its detail lines often accounts for a large share of elapsed time.
  • Planning versus execution time: the planning and execution lines at the bottom show whether the planner or the executor dominates.
  • Repeat runs: the first execution can differ from later ones, so compare several runs before drawing conclusions.

Before changing any setting, confirm that the node you identified is the same one that dominates the query's elapsed time in the application.

Which EXPLAIN options and fixes fit each symptom

This table pairs each EXPLAIN option or fix family with what it reveals or changes and the symptom it fits. Read the plan first to find the symptom, then use the matching row to choose the next step. Confirm option availability and defaults against the documentation for your PostgreSQL major version before relying on them.

Option or fixWhat it reveals or changesWhen it fits
EXPLAIN (no ANALYZE)Estimated plan shape, costs and estimated row counts without executing the queryPlanning a query before running it on large or write-heavy tables, or when execution is unsafe
EXPLAIN ANALYZEActual row counts, actual timings and loop counts next to the estimatesAny slow query where you need to see where the planner's estimates diverge from reality
BUFFERSShared, local and temp block hits and reads per node, showing whether time goes to disk I/O or cacheA node is slow and you need to know if it reads from disk or spills to temp files
VERBOSEOutput column lists and schema-qualified names per nodeConfirming which columns a node carries, useful when a wide row or unexpected sort is suspected
SETTINGSNon-default planner and configuration parameters that affected the planComparing a plan on two servers or after a configuration change that may have shifted plan choice
FORMAT JSON or YAMLMachine-readable plan output for tools and plan visualizersSharing plans across a team or feeding them into analysis tooling
WAL optionWAL records generated by data-modifying statementsWrite-heavy DML where you need to see the write volume of an INSERT, UPDATE or DELETE; confirm support in your version
Index or extended statisticsGives the planner access paths or correlation data it lacks; check the plan for index scans and corrected row estimates afterwardEstimates are far off on filtered columns or the plan scans many rows to return few
Per-column statistics target and ANALYZELarger sample for skewed columns so most common values and histograms are accurateRow estimates are wrong on a column with skewed value distribution even when an index exists
Query rewriteChanges the shape of the SQL so the planner can use a better join order, access path or early filterCorrelated subqueries, functions on indexed columns, or joins that multiply rows before filtering
Configuration changeAlters planner cost settings or memory limits that drive join and sort choicesThe plan is correct for the data but the workload or hardware makes the chosen method expensive; test on a copy first

How nested loop and hash join choices reveal the real problem

Join nodes in an EXPLAIN ANALYZE plan show where the planner's assumptions and the actual data part ways. The four patterns below each have a distinct plan symptom, a likely cause and a fix family, so you can move from the slow node to the change that addresses it.

Nested loop over many outer rows

A Nested Loop whose inner side is a scan that runs thousands or millions of times shows a loops count far above what the planner estimated. The usual cause is an outer row estimate that was too low, so the planner chose per-row lookups it expected to be cheap. Check the loops value on the inner node next to its estimated rows. The fix family is statistics and indexing: refresh or raise the statistics target on the join columns, add an index on the inner join key, or rewrite the query so fewer outer rows reach the join.

PostgreSQL docs

Hash join spilling to disk

A Hash node that reports batches above one, or a Hash Join with temporary file usage in the buffers output, means the hash table did not fit in memory and was written to disk in multiple passes. Look at the estimated size of the hashed input, since an underestimate sizes the hash too small. The fix family is memory and estimates: correct the row estimate with better statistics, reduce the hashed input by filtering or projecting earlier, and review work_mem and hash_mem_multiplier for the query, not the whole server.

Merge join on sorted input

A Merge Join is efficient when both inputs already arrive sorted on the join key, but the plan often shows explicit Sort nodes beneath it that dominate the timing. Compare the sort actual time with the rest of the join, and check whether a sort spilled to disk. The fix family is index order and sort reduction: an index that matches the join and filter columns can supply sorted rows directly, and removing unneeded columns from the sorted input cuts the sort cost. Confirm the choice of join method after each change, because the planner decides it.

Misestimated join order

When a join's estimated rows differ from actual rows by a large factor, every join above it is planned on the wrong numbers. The plan may join a large table first and filter later, or pick a join method that suits the estimate but not the data. Trace the estimate error to the lowest node where it first appears, since that is the true starting point. The fix family is statistics on correlated or skewed columns, such as extended statistics, and query structure, such as breaking up a query so each intermediate result is smaller.

Parameter-dependent plans

A query that is fast for one value and slow for another often uses a generic plan cached for a prepared statement, chosen without knowing the parameter. Compare a plan from EXPLAIN ANALYZE with literal values against the plan the application runs. A join method that suits common values can be wrong for rare ones. Confirm how the driver and connection pooler send statements before drawing conclusions, since a pooler can change which plan is reused. The fix family is application and configuration: align how statements are prepared, and test the plan for the parameter values that cause trouble.

How to run a safe EXPLAIN ANALYZE investigation step by step

This sequence turns a slow query report into a verified fix by capturing the exact query, reproducing it on comparable data, measuring the plan before and after each change, and confirming the result with repeated runs.

  1. Capture the exact query and its parameters

    Start from the statement that is actually slow, not a simplified version written from memory. Pull the normalized text and timing figures from pg_stat_statements, or the full text and duration from the server log if log_min_duration_statement is set, and record the bind values the application sent. The database administrator or the application owner should confirm which parameter values are typical and which are rare, because a plan chosen for one value can be wrong for another. The step is done when you have the literal query text, a sample of real parameter values, the database name, and the role that ran it.

  2. Check statistics freshness and settings on the source

    Before reading any plan, confirm the planner has accurate inputs. Check when each table was last analyzed and vacuumed using pg_stat_user_tables (last_analyze, last_autoanalyze, n_mod_since_analyze), and note any table that has changed heavily since its last analysis. Record the planner settings that affect plan choice, such as work_mem, random_page_cost, effective_cache_size, jit, and any session overrides the application sets. Compare these with the production values, because a plan produced under different settings tells you little about production. The step closes when you have a written list of stale tables and settings that differ from production.

  3. Reproduce the query on a comparable copy

    Restore a recent copy of the database that has data volumes, distributions and indexes close to production. A schema-only copy will give plans that look fine and say nothing about the real workload. Confirm the copy matches production in row counts for the affected tables, index definitions, and the PostgreSQL major and minor version, and run ANALYZE on the copy so its statistics reflect its data. Keep the copy's cache state in mind: a first run after restore reads from disk, while production may serve the same data from memory. The step is done when the copy's row counts, index list and version match production closely enough that you can explain any remaining differences.

  4. Capture the baseline plan with buffers and timing

    Run EXPLAIN (ANALYZE, BUFFERS, VERBOSE) on the reproduced query with the sample parameter values. For a data-changing statement such as UPDATE or DELETE, wrap the command in BEGIN and ROLLBACK, and use a copy rather than production, so the test leaves no changes behind. Save the full output, and do not trust a plan without the actual timing and buffer counts, since they show where the time and I/O went. Note the total execution time, the planning time, and any node where estimated and actual row counts differ by a large factor. The step closes when the baseline output is saved with the settings and statistics state recorded in the earlier steps.

  5. Diagnose the node that dominates the cost

    Read the plan from the innermost node outward and find the node with the largest actual time, or the one that loops many times, since the time shown for a looping node is per loop. Check whether the planner's row estimate for that node is far from the actual count, which points to statistics or correlated column problems, and check whether the join method suits the row counts involved, such as a nested loop running over a large outer set or a hash join spilling to disk. Look at buffer counts for reads that miss shared buffers and for temporary block writes that show sorts or hashes exceeding memory. The step is done when you can name the one or two nodes responsible and state the mismatch or resource problem in one sentence each.

  6. Apply one change and compare plans

    Make a single change on the copy, such as creating an index, running ANALYZE on a table, raising a column's statistics target, creating extended statistics, or rewriting the query. Change one thing at a time so the effect on the plan is attributable. Run EXPLAIN (ANALYZE, BUFFERS) again with the same parameters and place the new output beside the baseline. Confirm the plan node you targeted changed and that the row estimate moved closer to actual, and check that no other query path regressed by re-running the other statements from the capture list. The step closes when the before and after plans are recorded side by side with the change that produced them.

  7. Verify with repeated runs and a cold-cache check

    Run the improved query several times and discard the first run when comparing warm-cache timings, then also measure a run after clearing the cache or restarting on a test system where that is possible, so you know how it behaves when data is not in memory. Repeat the check across the sample parameter values, including rare ones, because a fix that helps common values can make rare values worse. Confirm the result holds under the concurrency the application produces, using a load test if the query runs hot. The step is done when timings are stable across runs, the cold and warm results are both recorded, and the rare parameter cases have been checked.

  8. Promote the change and record the evidence

    Apply the verified change to production through your normal change process, such as a reviewed migration for an index or a code change for a rewrite, and schedule index builds with CREATE INDEX CONCURRENTLY where a lock on a busy table is unacceptable. After the change, check pg_stat_statements again for the same query and confirm the mean time moved in the expected direction, and check that pg_stat_user_tables shows the affected table analyzed. Keep the before plan, after plan, settings and statistics state in the change record so the next reviewer can see why the change was made. The step closes when production timing for the query confirms the lab result and the evidence is filed with the change.

The decision path from a slow plan to a fix

The path starts with capturing the slow query and its EXPLAIN (ANALYZE, BUFFERS) output, then checks where estimated and actual row counts diverge and whether time goes to I/O or CPU. Each finding hands off to one fix branch: statistics, indexes, a join or query rewrite, or configuration review. Every branch ends in re-measuring the same query with the same parameters, so the fix is confirmed rather than assumed.

Decision path from a captured slow query to a re-measured fix.

Which fixes follow from indexes, statistics and query rewrites

Each diagnosis in an EXPLAIN ANALYZE plan points to a specific fix, and the fix should match the symptom rather than the first setting you remember. When the estimated and actual row counts diverge by a large factor, the planner is working from stale or too-coarse statistics. Run ANALYZE on the affected table first and check whether last_analyze or last_autoanalyze in pg_stat_user_tables is old. If the misestimate persists on a column with skewed values, raise that column's statistics target with ALTER TABLE ... ALTER COLUMN ... SET STATISTICS and re-analyze, then compare the plan again. When two filtered columns are correlated, the planner multiplies their selectivities as if they were independent and underestimates the result. That is the case for extended statistics, which the sibling topic on fixing bad query plans with extended statistics covers in detail.

When a plan scans a large table to return a few rows, or sorts a big set just to take the first few, the fix is usually an index on the filter or sort columns. Choose the index type to match the operator in the predicate, using the sibling topic on choosing PostgreSQL index types as the reference. A B-tree index serves equality, range and ordering conditions, while GIN, GiST and BRIN suit other access patterns. Check the plan again after creating the index, and confirm that the planner actually uses it. Sometimes a function wrapped around a column, an implicit type cast or a leading wildcard in a LIKE pattern prevents index use. In those cases, rewrite the predicate so the indexed column stands alone, or build an expression index that matches the rewritten form.

Every index and every statistics object adds cost on the write path. Inserts, updates and deletes must maintain each index, and autovacuum and autoanalyze run more often on busy tables. Before creating an index, ask who owns the write load, how many indexes the table already carries, and whether pg_stat_user_indexes shows existing indexes that are never scanned. Test the change against a copy of production write traffic, not only the read query, and record the effect on insert latency and on disk use.

What to protect when running EXPLAIN ANALYZE on production data

EXPLAIN ANALYZE is the fastest way to see why a query is slow, but it runs the statement for real. The cards below cover the risks that come with that: side effects, access, data exposure, logs and change control, so the diagnosis itself does not become the incident.

Running the statement executes it

EXPLAIN ANALYZE executes the query and reports actual timings, so an INSERT, UPDATE, DELETE or a function with side effects changes data. Wrap write statements in a transaction and roll back, and take the plan from a replica or a restored copy when the statement is heavy. Check locks too, because a long scan can hold locks and block writers. Confirm the statement is read-only before you run it on a primary.

Replication options

Roles needed to view plans

Running EXPLAIN ANALYZE needs the privileges to execute the query, and reading the query text from pg_stat_statements or logs needs extra access. Decide which roles may see other users' query text, since it can reveal table and column names. Grant those roles through a documented group, not by making engineers superusers. Review the role list at the same time as your authentication settings.

Authentication methods

Literal values in plan output

Plan nodes print filter conditions with literal values, such as an account number or an email address in a Filter line. Those values can end up in tickets, chat or shared screenshots. Replace literals with placeholders when you share a plan, and keep full plans inside the systems that already hold the data. Ask your compliance team whether plan text counts as personal data under your policies.

Logging slow statements

Settings such as log_min_duration_statement write slow statements to the server log, and auto_explain can record plans for slow queries. Both can capture literal values and query text in log files that many people can read. Set thresholds that match your investigation needs, restrict who can read the log, and confirm your log retention and rotation rules before you enable plan logging on a busy system.

Change control for indexes and settings

An index created on a large table can take heavy I/O and locks, and a configuration change such as a planner setting can shift plans across the whole workload. Record each change with the plan before and after, the test evidence and a rollback step. Build indexes concurrently where supported, apply them in a window your change process approves, and review the effect on write-heavy tables.

Questions teams ask before hiring help with slow query tuning

What drives the effort of a query tuning engagement?

The effort follows the number of slow queries, how many tables and indexes each one touches, and how much of the problem sits in data distribution rather than SQL text. A query that joins four large tables with skewed values takes longer to diagnose than a single-table filter missing an index. Effort also grows with the number of environments involved, such as production, staging and a reproduction copy, and with how many changes the client's change process requires before anything ships. Ask any provider to break the quote into analysis, fix design, testing and handover so you can see which part carries the cost.

How long does a query tuning engagement take?

Duration depends mainly on how many queries are in scope and how much of their data access must be measured before a fix is chosen. A short list of well-understood queries can be reviewed quickly, while a backlog spread across many tables and workloads needs repeated plan capture, fix, and retest cycles. Data volume matters because plans on a small staging copy can differ from production, so the timeline should include time to obtain representative data or run tests against a suitable copy. Ask the provider to state the number of queries in scope, the environments used for testing and the change windows assumed, then compare the schedule against those inputs.

What must our team provide before tuning starts?

Three things usually decide whether the work moves quickly: access, representative data and change windows. Access means a read-capable connection to the database, the ability to run EXPLAIN (ANALYZE, BUFFERS) on real parameter values, and visibility into pg_stat_statements if it is enabled. Representative data means a recent copy or a sanitized snapshot with comparable row counts and value distribution, since statistics and join choices depend on it. Change windows define when index builds, ANALYZE runs and configuration reloads can happen. Confirm with your security team how access is granted and whether production query text can leave your network.

Can our in-house DBA team tune these queries alone?

Often yes, provided the team has time, access to representative data and a process for testing changes. Reading a plan is a learnable skill: compare estimated and actual row counts, check buffer reads against the work done, and find which node carries most of the time. The harder part is judging trade-offs, such as whether an extra index slows writes enough to matter or whether a rewrite changes results. Many teams keep the DBA as owner and bring in outside help for a focused backlog or a second review. Decide early who approves changes, who owns the index and statistics decisions, and how fixes are documented.

What recurs after the first round of query fixes?

The first round fixes the queries that were worst at the time, but the work does not end there. Data grows, value distributions shift and application releases add new query shapes, so plans that were fine can regress. Autovacuum and ANALYZE need to keep statistics current, and new indexes add write cost that should be reviewed. Recurring work includes reviewing the top queries after each release, retesting plans after large data loads, and removing indexes that no longer serve a query. Ask whether the provider offers ongoing review or retesting and what it covers, since those are typically scoped separately from the initial engagement.

Does DeployOpen guarantee a specific speed improvement?

No. DeployOpen does not promise a fixed improvement percentage or response time, because the result depends on the workload, hardware, data and application behavior. What DeployOpen does is agree the scope in writing, measure the queries in scope with plans and buffer data, implement the chosen fixes in your infrastructure and document what changed and why. Before accepting a proposal, ask for the measurement method, the test environment and the acceptance criteria for each query, so the result can be checked against evidence rather than a promise.

Will tuning changes affect our security or compliance evidence?

Usually only in limited ways, but the changes should be recorded. Index changes, statistics targets and query rewrites alter the database objects that your change management and access reviews track, so each one should go through the same approval path as other schema changes. Plan captures can include query text and parameter values, which may contain personal or regulated data, so restrict where captures are stored and who can read them. If an auditor asks how a change was approved, the written scope, test results and rollback notes should answer that question.

How DeployOpen scopes and delivers PostgreSQL query tuning

DeployOpen approaches slow-query work as a fixed-scope engagement on the PostgreSQL servers you run. We start from captured plans of the queries your users actually feel, then agree written changes, test each one against the same data, and hand over the evidence along with the tuned database.

How we scope

  • Confirm which slow queries, applications and time windows the written scope covers before any plan is read.
  • Record the PostgreSQL version, hardware, data volumes and current configuration so plan results can be compared fairly.
  • Agree in writing whether the work includes query rewrites, index changes, statistics changes or only findings.

How we build

  • Capture EXPLAIN ANALYZE with BUFFERS for each target query, under a representative load and a copy of production-like data.
  • Compare estimated and actual row counts per node to locate where the planner misjudged selectivity or join size.
  • Test each proposed index, statistics target or query rewrite separately, and record its effect on timing and buffer reads.

How we hand over

  • Deliver a document for each query with the before and after plans, the reasoning, and the exact DDL or query changes.
  • Provide rollback statements for every index and statistics change, plus notes on the migration order for your environment.
  • Walk your database and application engineers through the findings so they can read the next plan without us.

How we support

  • Engagements are fixed-scope, so scope, deliverables and timelines are agreed in writing before work starts.
  • Ongoing support, upgrades and continuous testing are available as a retainer when query behavior changes with new data or releases.
  • Confirm with us during scoping how plan regressions after a PostgreSQL major upgrade will be reviewed and by whom.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.