查找开销最大的查询(pg_stat_statements:总时间和平均时间)
PostgreSQL性能命令
-- By total time: queries consuming the most server time
SELECT queryid,
calls,
round(total_exec_time::numeric, 1) AS total_ms,
round(mean_exec_time::numeric, 2) AS mean_ms,
round(stddev_exec_time::numeric, 2) AS stddev_ms,
round((100 * total_exec_time / sum(total_exec_time) OVER ())::numeric, 1) AS pct_total,
rows / NULLIF(calls, 0) AS rows_per_call,
left(regexp_replace(query, '\s+', ' ', 'g'), 120) AS query
FROM pg_stat_statements
WHERE dbid = (SELECT oid FROM pg_database WHERE datname = current_database())
ORDER BY total_exec_time DESC
LIMIT 20;
-- By mean time per call: individually slow queries
SELECT queryid,
calls,
round(mean_exec_time::numeric, 2) AS mean_ms,
round(max_exec_time::numeric, 2) AS max_ms,
round(mean_plan_time::numeric, 2) AS mean_plan_ms,
left(regexp_replace(query, '\s+', ' ', 'g'), 120) AS query
FROM pg_stat_statements
WHERE calls >= 50
ORDER BY mean_exec_time DESC
LIMIT 20;作用
列出当前数据库中消耗服务器时间最多的规范化查询及其在总量中的占比;第二个查询列出单次调用最慢的查询。
适用场景
CPU/IO 负载上升或用户反映"数据库很慢"时的第一站;用于决定从哪里开始调优。
注意
在将 pg_stat_statements 加入 shared_preload_libraries、重启服务器并在数据库中运行 CREATE EXTENSION 之前,它不会收集任何数据。数值是自上次重置以来的累计值。stddev_ms 相对 mean_ms 较高,表示计划或数据分布在各次调用之间存在差异。mean_plan_time 只有在 pg_stat_statements.track_planning = on 时才会填充(默认 off;启用会增加开销)。查看其他用户的查询文本需要超级用户或 pg_read_all_stats 角色。