AdvancedPerformance & Indexes

Identify slow queries with pg_stat_statements

The query

SQL
-- Enable extension in postgresql.conf: shared_preload_libraries = 'pg_stat_statements'
CREATE EXTENSION pg_stat_statements;

-- Top 10 slowest queries by total execution time
SELECT
  ROUND(total_exec_time / 1000, 2) AS total_seconds,
  calls,
  ROUND(mean_exec_time, 2) AS avg_ms,
  ROUND(stddev_exec_time, 2) AS stddev_ms,
  rows,
  LEFT(query, 120) AS query_preview
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;
Tested against PostgreSQL 16

Note

pg_stat_statements is essential for production tuning. Shows which queries consume most resources.