Show slow queries (pg_stat_statements)

Top 10 slowest queries by total execution time

psql -U postgres -d mydb -c "SELECT round(total_exec_time::numeric,2) ms, calls, round((total_exec_time/calls)::numeric,2) avg_ms, query FROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 10;"

tool
postgres29 commands
tags
postgresmonitoringperformance

More postgres commands

  • psql -U postgres -c "SELECT pid, now()-query_start AS duration, state, left(query,80) FROM pg_stat_activity WHERE state <> 'idle' ORDER BY duration DESC;"

    Running queries with duration and truncated SQL

  • psql -U postgres -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE now()-query_start > interval '5 min' AND state = 'active';"

    Terminate all queries running longer than 5 minutes

  • psql -U myuser -d mydb -c "SELECT schemaname, tablename, pg_size_pretty(pg_total_relation_size(schemaname||'.'||tablename)) size FROM pg_tables ORDER BY pg_total_relation_size(schemaname||'.'||tablename) DESC LIMIT 20;"

    Top 20 tables by total size including indexes and TOAST

  • psql -U myuser -d mydb -c "SELECT relname, indexrelname, idx_scan, idx_tup_read FROM pg_stat_user_indexes ORDER BY idx_scan DESC LIMIT 20;"

    Which indexes are actually being used and how often

  • psql -U myuser -d mydb -c "SELECT schemaname, tablename, indexname, idx_scan FROM pg_stat_user_indexes WHERE idx_scan = 0 AND NOT indisprimary ORDER BY pg_relation_size(indexrelid) DESC;"

    Indexes that have never been scanned — safe to drop candidates

all 29 postgres commands