← All posts PostgreSQL

Use pg_stat_statements to rank cumulative PostgreSQL query cost

The Tryssh team ·

For pg_stat_statements, the safest approach is a bounded operational change, not a command pasted without context. This runbook starts with effective state, shows the smallest candidate action, and finishes by repeating the real user or system path.

TL;DR: Pg_stat_statements groups normalized statements and accumulates planning and execution statistics; totals reflect the collection window, not one trace. Capture a baseline with SELECT extname, extversion FROM pg_extension WHERE extname = 'pg_stat_statements';, make the reviewed change only when the evidence matches, then verify with SELECT stats_reset FROM pg_stat_statements_info; and keep the rollback ready.

Audience: database operators who can run read-only SQL and distinguish a diagnostic session from application traffic. This guide assumes familiarity with PostgreSQL operations and a change window appropriate to the system.

Use pg_stat_statements to rank cumulative PostgreSQL query cost observe, interpret, change, and verify workflow

The direct answer

Top statements are interpreted with calls, total time, mean time, rows, and the known reset window. That is the success condition for pg_stat_statements; command completion by itself is not enough.

The important boundary is client session, transaction, lock manager, planner, executor, storage, WAL, and replica state. Pg_stat_statements groups normalized statements and accumulates planning and execution statistics; totals reflect the collection window, not one trace. If an observation does not identify which side of that boundary failed, collect a narrower observation before changing state.

How the mechanism works

For pg_stat_statements, use this mental model: PostgreSQL accepts work through sessions and transactions, plans against statistics, coordinates concurrency with locks and MVCC, and makes durable changes through data pages plus WAL. The model prevents a common mistake—treating configuration text, control-plane acceptance, process state, and end-user behavior as the same proof.

Follow four stages:

  1. Observe: identify the exact host, object, version, owner, and active configuration.
  2. Interpret: write the expected result, the abnormal result, and what would remain inconclusive.
  3. Change: apply one reviewed action at the narrowest layer that contradicts the baseline.
  4. Verify: repeat the original path and compare the same evidence, including adjacent safety controls.

Preflight and safety boundary

Use a dedicated diagnostic session with timeouts, capture the server version and active workload, and rehearse any blocking or destructive command on a representative copy.

Before pg_stat_statements, record UTC time, the current version or digest, the exact target, recent changes, and who owns the workload. The rollback for this runbook is: drop the extension only after another collection path exists, restore preload configuration on a planned restart, and preserve exported statistics.

Do not continue if the target identity is ambiguous, the current state cannot be saved, the only recovery session would be at risk, or the proposed command affects more objects than the brief names.

Capture the read-only baseline

Run these commands one at a time. Replace example names and addresses deliberately; do not paste production secrets into a transcript.

SELECT extname, extversion FROM pg_extension WHERE extname = 'pg_stat_statements';
SELECT stats_reset FROM pg_stat_statements_info;
SELECT calls,total_exec_time,mean_exec_time,rows,query FROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 20;

Interpret the baseline before moving on:

  • Expected: top statements are interpreted with calls, total time, mean time, rows, and the known reset window.
  • Abnormal: one rare slow call hides under a low total, query IDs changed, or tracking configuration excludes relevant statements.
  • Inconclusive: missing output can also mean the wrong context, permissions, namespace, log window, binary, or target. Prove those assumptions before treating absence as health.

Save the decisive output, exit status, and timestamp. Redact credentials, customer data, private topology, tokens, and complete environment dumps.

Apply the smallest candidate change

The following is state-changing example syntax, not an instruction to run it unchanged:

CREATE EXTENSION IF NOT EXISTS pg_stat_statements;

For pg_stat_statements, the proposed change is acceptable only when the read-only baseline predicts its effect and the rollback is available. The key risk is: resetting statistics during an incident destroys the baseline needed to compare before and after.

Prefer an immutable artifact, validated configuration, dry-run, transaction, candidate object, or staged target when the tool supports one. Record the exact command and UTC time so later telemetry can be correlated to the change.

Verify the result from the outside in

SELECT stats_reset FROM pg_stat_statements_info;
SELECT calls,total_exec_time,mean_exec_time,rows,query FROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 20;
SHOW pg_stat_statements.track;

Verification for pg_stat_statements has three layers:

  1. The control plane or command reports the intended effective state.
  2. The process, resource, or data path reflects that state without a new pressure signal.
  3. The original user-visible or dependent-system path succeeds from an independent vantage point.

If SELECT stats_reset FROM pg_stat_statements_info; succeeds but the original path still fails, stop. The change may have repaired a local symptom while DNS, policy, routing, caching, dependency, or client state remains broken.

Failure branches

The baseline does not match this runbook

When one rare slow call hides under a low total, query IDs changed, or tracking configuration excludes relevant statements, do not force the candidate command. Return to identity and scope, compare a healthy peer only through effective settings, and name a new falsifiable mechanism.

The change succeeds but behavior does not

A successful CREATE EXTENSION IF NOT EXISTS pg_stat_statements; proves that one interface accepted a request. It does not prove convergence, readiness, data compatibility, external routing, or client recovery. Re-run the same evidence at each downstream boundary.

The change makes the system worse

Execute the written rollback: drop the extension only after another collection path exists, restore preload configuration on a planned restart, and preserve exported statistics. Preserve the failed candidate and relevant logs long enough to explain the outcome; do not destroy the evidence with broad cleanup or repeated restarts.

Operator checklist

  • Confirm the exact target, context, identity, version, and active owner.
  • Capture the read-only baseline and one disconfirming observation.
  • Label CREATE EXTENSION IF NOT EXISTS pg_stat_statements; as state-changing during review.
  • Keep recovery access and rollback independent of the path being edited.
  • Change one layer, record UTC time, and wait for its real convergence boundary.
  • Verify the original path, adjacent controls, resource pressure, and persistence.
  • Update the runbook when observed behavior differs from the source-reviewed model.

Investigate it in Tryssh

Tryssh keeps the command, approval boundary, output, and verification beside the host conversation.

Tryssh can preserve this evidence loop and show a state-changing command for human approval. It does not make the operator's identity, recovery access, rollback, or platform authority decisions.

Evidence and review status

This pg_stat_statements runbook was source-reviewed on 2026-07-29 against current first-party documentation. The commands are illustrative and use example targets. The page does not claim that the change was reproduced across every distribution, managed service, version, network, or workload.

Limitations and trade-offs

Resetting statistics during an incident destroys the baseline needed to compare before and after. Managed platforms may generate configuration, restrict privileges, replace local state, or expose a different control plane than the upstream project. Confirm the installed version and provider contract before applying a repair.

Search visibility is not proof of operational correctness. Treat this page as a decision aid, preserve independent recovery, and stop when the evidence contradicts its assumptions.

Related operator runbooks

Continue with pg_stat_activity, EXPLAIN ANALYZE production, the PostgreSQL operations foundation guide, and the SSH hardening checklist.

Sources and further reading