Skip to content

Statements by total time

The statements that cost the most in aggregate: mean time × calls. Optimising the top three usually moves the whole server.

PostgreSQL · SQL
SELECT LEFT(query, 160) AS statement,       calls,       ROUND(total_exec_time::numeric, 0) AS total_ms,       ROUND(mean_exec_time::numeric, 2) AS mean_ms,       rows,       ROUND(100.0 * shared_blks_hit / NULLIF(shared_blks_hit + shared_blks_read, 0), 1) AS cache_hit_pctFROM pg_stat_statementsORDER BY total_exec_time DESCLIMIT 20

Needs something on the server: The pg_stat_statements extension must be installed and in shared_preload_libraries.

This query is part of the "PostgreSQL health" pack: connect the database in DataRunner and install the whole pack at once, with queries and dashboard.

What this query shows

The slowest query is rarely the one that costs the most. A statement that takes 20 ms but runs two million times a day uses far more of the server than one that takes 10 seconds once. This query ranks statements by total time, which is what you want to cut.

It reads pg_stat_statements, the extension that keeps one row of counters for each normalized statement, and returns the top 20 by total_exec_time. Run it when the server is busy and you do not know why, or before a tuning session.

Turn on pg_stat_statements first

The view does not exist until you load the extension. It needs a restart, because the library has to be preloaded.

  1. Add it to postgresql.conf: shared_preload_libraries = 'pg_stat_statements'
  2. Restart PostgreSQL.
  3. In each database you want to read, run CREATE EXTENSION pg_stat_statements;

On managed services such as RDS, Cloud SQL or Azure, the preload is usually a parameter group setting. Check your provider's page for the exact name.

How to read each column

  • statement: the first 160 characters of the normalized text. Constants appear as $1, $2.
  • calls: how many times it ran.
  • total_ms and mean_ms: total and average execution time in milliseconds. The query sorts by total.
  • rows: total rows returned or affected across all calls.
  • cache_hit_pct: share of shared buffer reads served from memory for that statement. Low values on a hot statement point to missing indexes or a large scan.

What to do about it

Take the top three rows and look at each one with EXPLAIN (ANALYZE, BUFFERS) using realistic parameters. High calls with a low mean_ms is an application problem: caching, batching or an N+1 pattern. Low calls with a high mean_ms is a query or index problem.

EXPLAIN (ANALYZE, BUFFERS)SELECT * FROM orders WHERE customer_id = 42 AND status = 'open';

To measure a change fairly, clear the counters and let new traffic accumulate.

SELECT pg_stat_statements_reset();

Compare a high mean_ms against a normal one for the same statement over several days before you conclude anything. One run after a restart tells you little.

Limits of this query

  • The columns total_exec_time and mean_exec_time exist from PostgreSQL 13. On version 12 and older they are called total_time and mean_time, and this query will fail.
  • Other users' statement text is hidden unless your role is a superuser or in pg_read_all_stats.
  • The extension keeps a limited number of statements (pg_stat_statements.max, 5000 by default). Rare statements can be evicted.
  • Counters accumulate since the last reset, so an old, heavy workload can hide today's one.

Run it on a schedule in DataRunner

Connect the database to DataRunner, paste this query or start from the template, approve the SQL, then pick a schedule and a channel. Weekly keeps a trail of the heaviest statements, and the run history lets you see which ones climb. Each run executes the query on your database and delivers the result as CSV, Excel, PDF or inline HTML by e-mail, Slack, Telegram, Discord, WhatsApp (beta), a signed webhook or Google Sheets.

Every run is kept in the run history, so you can set today's result next to last week's. A schedule carries its own time zone, so a Monday at 8:00 is your Monday.

If the database sits in a private network, the bridge agent opens the connection from the inside out, so you do not need to open an inbound port.

Frequently asked questions

How do I find the slowest queries in PostgreSQL?
Enable pg_stat_statements and sort its view by total_exec_time, as this template does. For the worst single executions, also look at max_exec_time. Another source is log_min_duration_statement, which writes slow statements to the log.
How do I enable pg_stat_statements?
Add pg_stat_statements to shared_preload_libraries in postgresql.conf, restart the server, then run CREATE EXTENSION pg_stat_statements in the database. The restart is required, and the extension is not on by default.
Why does the query fail with "relation pg_stat_statements does not exist"?
The extension was not created in the database you are connected to. Run CREATE EXTENSION pg_stat_statements there. If the error mentions the library, shared_preload_libraries has not been set or the server was not restarted.
Should I sort by total time or mean time?
Sort by total time to find what costs the server the most overall, and by mean time to find individual slow statements. Total time usually gives the bigger win, since it counts how often a statement runs.