dataiotech Labs
dbaguidedbaguideDBAdataxtoolsdataopsphere
Scripts Library/postgresql/#5
Script #5
postgresql
Performanceread-onlyMin Version: 13 (eski sürümde `total_time`, `mean_time`)

Top 20 Most Expensive PostgreSQL Queries with pg_stat_statements

Ranks queries by total time, call count and mean time. Tells you which query to tune first.

#pg_stat_statements#top-queries#tuning
postgresql · sql
-- Gerekli: CREATE EXTENSION pg_stat_statements; (shared_preload_libraries)
SELECT round(total_exec_time::numeric, 0) AS total_ms,
       calls,
       round(mean_exec_time::numeric, 2)  AS mean_ms,
       round((100 * total_exec_time / sum(total_exec_time) OVER ())::numeric, 2) AS pct_total,
       rows,
       left(query, 150) AS query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 20;
Operational Notes & Remediation Guidance

Verify in a staging environment prior to running in production. This is a read-only diagnostic query; it does not acquire exclusive locks.

Production Safety & Execution Standards
  • This script is designed for read-only diagnostics; it does not alter schema or modify data directly.
  • Prior to executing on production systems under high load, verify the target database version (Min. Version: 13 (eski sürümde `total_time`, `mean_time`)).
  • Exercise caution with mutating actions (e.g., terminating sessions or dropping indexes) referenced in the notes section.