Cookbook recipe

Find your slowest queries with pg_stat_statements

Applies to PostgreSQL 13–17 Last reviewed May 2026 Grounded in source
Estimated investigation4 min

Scenario

The database feels slow but you do not know which queries are to blame. pg_stat_statements ranks every normalized query by total time so you can target the real offenders. Diagnose it Enable the extension, then rank…

Investigation Path

The database feels slow but you do not know which queries are to blame. pg_stat_statements ranks every normalized query by total time so you can target the real offenders.

Diagnose it

Enable the extension, then rank by total execution time:

CREATE EXTENSION IF NOT EXISTS pg_stat_statements;

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

Why it happens

Total wall-clock cost is calls * mean time. A fast query called millions of times can hurt more than one slow report. Ranking by total time finds what actually consumes the server.

This is a Pro lesson

Get every Learning Pathway and cookbook recipe — grounded in PostgreSQL source code, with diagnostics, fixes, and prevention for each topic.

Continue this lesson to learn:

  • How to fix it
  • Prevent it next time
  • Related & next steps
  • All 36 Learning Pathway lessons
  • 170+ cookbook recipes
  • Source-grounded diagnostics & fixes

Secure checkout Cancel anytime Source-grounded

Career Impact

This scenario builds production judgment and operational confidence under pressure.

Open Career Dashboard →

Keep going

Related & next steps

Was this helpful?

← All cookbook recipes