Back to Blog
DatabaseTutorials

PostgreSQL Performance Tuning: EXPLAIN, Indexes and Query Optimization

Mustaf Abubakar
Mustaf Abubakar
•14 min read
PostgreSQL Performance Tuning: EXPLAIN, Indexes and Query Optimization

A slow database query can be a symptom of many different problems: an inefficient access path, inaccurate planner estimates, excessive sorting, lock contention or an application asking for far more data than it actually needs. Adding an index without understanding the bottleneck may improve one statement while introducing unnecessary storage and write overhead.

PostgreSQL provides a practical set of tools for diagnosing query performance. This guide uses PostgreSQL 18 as a reference version and focuses on a repeatable workflow: measure the workload, inspect execution plans, test a targeted improvement and verify the result. The examples use synthetic data and do not depend on confidential production systems.

1. Start with the workload, not an individual query

A database administrator investigating slow requests should first determine which statements contribute most to the application's performance problems. A query that takes 20 seconds once a month may be less important than a query that takes 50 milliseconds and runs millions of times.

Consider the following fictional workloads:

QueryCallsAverage durationTotal execution time
Daily report210 seconds20 seconds
Account lookup50,00020 milliseconds1,000 seconds
Search request1,000500 milliseconds500 seconds

These numbers are illustrative, not benchmark measurements. They show why total execution time and frequency matter alongside individual latency. A critical interactive endpoint may also deserve attention because of its latency objective, even if its aggregate cost is small.

The PostgreSQL pg_stat_statements extension can help identify expensive statement patterns. When configured and enabled by an authorized administrator, it records aggregate statistics about normalized statements.

SELECT queryid,
       calls,
       round(total_exec_time::numeric, 2) AS total_ms,
       round(mean_exec_time::numeric, 2) AS mean_ms,
       rows
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 20;

This query assumes the extension is already available in the database. Enabling it requires the appropriate shared_preload_libraries configuration and a server restart if it is not already preloaded, followed by extension creation in the relevant database. Do not change a production server's configuration without an approved maintenance process.

Statistics are cumulative over their collection period and may reset. Capture snapshots over comparable intervals. The mean also does not describe tail latency, so correlate database metrics with application latency percentiles and request traces.

See the pg_stat_statements documentation for configuration, access controls and field definitions.

2. Read the execution plan before making changes

The EXPLAIN command displays the plan chosen by PostgreSQL. It shows operations such as sequential scans, index scans, joins and sorts, together with estimated costs and output cardinalities.

Start with an ordinary EXPLAIN:

EXPLAIN
SELECT order_id, created_at, amount_minor
FROM demo_orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 20;

Planner cost values are relative units used to compare alternatives, not elapsed milliseconds. The estimated row count describes the rows emitted by a node, which is not necessarily the number of rows it had to examine.

For an authorized query in a suitable test environment, collect execution statistics as well:

EXPLAIN (ANALYZE, BUFFERS, TIMING OFF)
SELECT order_id, created_at, amount_minor
FROM demo_orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 20;

ANALYZE causes the statement to execute. Even a SELECT can call functions with side effects, acquire locks or consume significant resources. Never run an expensive diagnostic indiscriminately against a live database. Use a staging environment with representative data whenever practical, and apply appropriate resource and statement-time limits.

TIMING OFF avoids collecting detailed per-node timing while retaining row counts and overall execution time. BUFFERS provides information about buffer activity. A shared buffer read does not necessarily mean a physical storage device read, because the operating system may already have cached the page.

Pay attention to these signals:

SignalQuestion to investigate
Estimated versus actual rowsDid the planner understand the data distribution?
Rows removed by filterIs the query examining many unnecessary records?
LoopsIs an inner operation repeated many times?
Sort or hash spillIs the operation writing temporary data?
Buffer activityHow much data is being touched?

Actual rows are reported as averages per loop when a node runs repeatedly. A small row count can therefore hide substantial aggregate work. Read the tree from its underlying operations toward the root, and remember that parent-node buffer counts include child activity.

The official Using EXPLAIN guide provides examples of plan interpretation.

3. Build a reproducible index experiment

Create an isolated lab database and use a dedicated synthetic table. Do not use these setup statements in an existing application schema.

CREATE TABLE demo_orders (
    order_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    customer_id integer NOT NULL,
    created_at timestamptz NOT NULL,
    amount_minor integer NOT NULL
);

INSERT INTO demo_orders
    (customer_id, created_at, amount_minor)
SELECT 1 + (g % 1000),
       timestamptz '2026-01-01 00:00:00+00'
           + g * interval '1 minute',
       100 + (g % 10000)
FROM generate_series(1, 200000) AS s(g);

ANALYZE demo_orders;

The table contains 200,000 synthetic records distributed among 1,000 customers. There is initially no index specifically supporting the customer filter and timestamp ordering. The primary key index supports the order identifier.

Execute the earlier EXPLAIN ANALYZE example and save the plan. Then create an index designed for the query:

CREATE INDEX demo_orders_customer_created_idx
ON demo_orders (customer_id, created_at DESC);

ANALYZE demo_orders;

Run the same diagnostic again. This index can support the equality condition on customer_id and provide rows in the requested timestamp order. The LIMIT allows execution to stop once enough matching rows have been found, subject to visibility and other plan conditions.

Do not assume a particular speedup or even a guaranteed index scan. The planner considers estimated costs, table size, available paths and selectivity. Actual measurements depend on the environment. Compare plans, buffer activity and execution times across several runs under consistent conditions.

In a production migration, ordinary CREATE INDEX can block writes to the table. Evaluate CREATE INDEX CONCURRENTLY when appropriate, including its longer execution time, extra resource demands, transaction restrictions and possible invalid indexes after failure. Plan the operation with the database team.

4. Fix inaccurate estimates before forcing a plan

PostgreSQL relies on table statistics to estimate selectivity and choose between alternatives. When estimates differ substantially from actual row counts, an apparently poor plan may be the result of incomplete information.

Check whether automatic analysis is keeping pace with data changes. After a large authorized data load, a targeted ANALYZE may be appropriate. PostgreSQL also supports increased statistics targets for columns whose distributions are difficult to estimate.

Some predicates involve correlated columns. For example, a region and a city may not be independent. Extended statistics can help the planner account for certain relationships when estimating predicates.

Avoid treating planner switches as permanent fixes. Temporarily disabling a plan type in a controlled session may help investigate an alternative, but it does not establish that the alternative is suitable for the full workload.

Refer to ANALYZE and the performance tips chapter for statistics and planning considerations.

5. Understand why an index is not always the answer

Sequential scans are not inherently bad. If a query needs a large fraction of a table, scanning it may be cheaper than repeatedly accessing scattered heap pages through an index.

Indexes consume disk space and introduce maintenance work during writes. A wide covering index can reduce heap visits for some queries, but index-only scans also depend on visibility information. Adding every projected column can make the index significantly larger.

Review query patterns rather than building a separate index for every statement. Equality predicates, range predicates, sorting, join conditions and data distributions influence the appropriate column order. The index that benefits one workload may be unnecessary for another.

For pagination, applications that repeatedly request very deep OFFSET values may require the server to process and discard many records. A keyset pagination design using a stable unique ordering can reduce that work, although it changes the API contract and does not naturally support arbitrary page jumps.

6. Separate execution cost from waiting

A statement can be slow because it is waiting rather than actively processing data. Lock contention, connection pool exhaustion and storage pressure require different corrective actions.

An authorized monitoring role can inspect active sessions:

SELECT pid,
       state,
       wait_event_type,
       wait_event,
       now() - query_start AS query_age
FROM pg_stat_activity
WHERE state = 'active'
  AND pid <> pg_backend_pid()
ORDER BY query_start;

A wait event provides a point-in-time observation, not a complete diagnosis. Correlate repeated observations with workload metrics and transaction duration. Avoid terminating sessions automatically based on age alone; a long-running maintenance operation may be intentional.

When reviewing query text or exporting execution plans, redact customer identifiers and sensitive literals. Monitoring access itself should be limited because SQL text and plans can reveal internal data structures and business logic.

7. Verify changes as part of normal operations

Performance tuning is an experiment with a controlled before-and-after comparison. Record the original plan, dataset size, relevant database settings and workload characteristics. Apply one meaningful change at a time.

For each change, evaluate:

  • Query latency and total execution time across representative inputs.
  • Impact on concurrent reads and writes.
  • Index size, maintenance cost and temporary disk usage.
  • Lock behavior and operational risk during deployment.
  • Whether other important queries regress.

A faster test query does not guarantee an improvement in application throughput. Check the whole service under realistic concurrency. Define rollback criteria before a production change and verify that monitoring can distinguish a regression from ordinary workload variation.

Conclusion

Effective PostgreSQL performance tuning starts with evidence. Identify important statements, inspect execution plans, distinguish work from waiting, and choose improvements based on real access patterns. Use targeted indexes and current statistics rather than guessing at configuration changes.

The objective is not to eliminate every sequential scan or minimize one execution time in isolation. It is to meet application service objectives while maintaining predictable database behavior, operational safety and efficient resource use.

References and further reading

Comments

No comments yet

Be the first to share your thoughts!

Leave a Comment

Your email will not be published

0/1000 characters

Want to work together?

I'm always open to discussing new projects and opportunities.

Get in Touch