Improve and diagnose query performance

How to Test a Fix for a Slow PostgreSQL Query

Use a repeatable EXPLAIN ANALYZE loop to test whether a targeted PostgreSQL index improves a costly query without changing its results.

Editorial illustration for How to Test a Fix for a Slow PostgreSQL Query

To optimize a recurring slow query, start with one that matters to the workload, not one whose plan merely looks unusual. Run it with representative parameter values, record its result and measured plan, make one change tied to an observed bottleneck, then measure the same query again. An estimated plan can suggest what to investigate; it cannot establish a speedup.

Choose a query and a representative value

Suppose an application repeatedly asks for total line-item price by product above a threshold. Assume an existing line_items table with a comparable product_id column and a price column that can be summed. The SQL below is an illustration, not a reported test. Substitute a threshold that reflects the costly calls you actually need to improve.

SELECT product_id, SUM(price) AS total_price
FROM line_items
WHERE product_id > 80
GROUP BY product_id;

Use workload evidence to establish that this query consumes meaningful resources or time across its relevant calls. Keep the parameters with that evidence: a threshold that returns few rows may tell you little about calls that return many. Record the PostgreSQL release, relevant settings, table characteristics, parameter value, and measurement conditions so the follow-up has a useful point of comparison. Do not change the predicate between measurements just to obtain a more attractive plan.

Record the result and measured baseline

Save the query's returned rows, then run this statement with the same threshold:

EXPLAIN (ANALYZE, BUFFERS)
SELECT product_id, SUM(price) AS total_price
FROM line_items
WHERE product_id > 80
GROUP BY product_id;

Plain EXPLAIN prints a plan without running the query. EXPLAIN ANALYZE runs it and adds actual execution information, including rows and timing. BUFFERS adds buffer activity. These distinctions matter when deciding whether a proposed fix worked: planner costs are estimates, not elapsed time. See the EXPLAIN walkthrough for the distinction between a planned query and a measured execution.

Read from the node doing the substantial work toward its parent nodes. For each, compare estimated rows with actual rows, note loops, and inspect actual time and buffer hits or reads. Actual row and time figures are per-loop averages, so a node executed repeatedly needs its loop count considered when interpreting its contribution. Also record the overall execution time rather than treating one node's estimate as the query's duration.

For a concrete reading example, a published line-items plan estimated 71 rows at GroupAggregate and reported 20 actual rows with loops=1. Its underlying index-only scan estimated and reported 112 rows. Those numbers belong to that source's dataset; they are not a baseline or a promised result for the SQL here. A difference between estimates and actual rows is a reason to investigate the estimate, not proof that an index is missing.

Test one change that fits the bottleneck

First check whether the plan points to outdated statistics rather than an indexing problem. PostgreSQL's planner selects a plan it expects to run fastest, and the documentation identifies manually running ANALYZE as one way to improve plan quality. If statistics are the suspected issue, run a targeted statistics update and measure again before adding an index:

ANALYZE line_items;

This ANALYZE updates planner statistics; it is not EXPLAIN ANALYZE, which executes and measures the query. In one reported example, a statistics update preceded a change from a sequential scan to an index scan. That observation does not predict what will happen here. If the query instead filters through an expression, check whether it matches the indexed expression: a documented example stopped using a function-based index when the query's expression changed.

If the baseline points to costly access to line_items for this filter, one candidate to test is:

CREATE INDEX items_product_id_price
ON line_items (product_id, price);

The leading product_id matches the filter, while price is the value being aggregated. A published example with an index in this order showed an index-only scan for a product_id > 80 filter, but its reported execution time is evidence about that example only. PostgreSQL can also consider a sequential scan, so neither creating this index nor seeing a particular plan node guarantees an improvement for your data. Review the schema change's deployment, locking, storage, and write-workload consequences before using a successful local test as a production change.

Measure again and check the answer

After the single candidate change, run the identical measurement:

EXPLAIN (ANALYZE, BUFFERS)
SELECT product_id, SUM(price) AS total_price
FROM line_items
WHERE product_id > 80
GROUP BY product_id;

Compare the baseline and follow-up in a comparable environment, using the same threshold and noting conditions that could affect buffer activity. Did the work-heavy node change? Do actual rows and loops still describe the expected work? Compare measured execution time and buffer hits or reads, not just estimated cost or the presence of an index scan. If the costly workload uses several materially different thresholds, repeat the comparison with those representative values before generalizing from one call.

Finally, run the original SELECT again and compare its returned groups and totals with the saved result. Retain the change only if the answer remains correct and the measured benefit for the relevant workload justifies its operational cost. If it does not, the useful outcome is a rejected hypothesis, not an excuse to declare victory from a tidier plan.

Find a note

Search by topic, title, or keyword.