pg_stat_statements 模块主要用来对数据库中执行的所有 sql 语句进行一些统计分析, 以便于用来监控和分析 postgres 数据库性能。
当 pg_stat_statements 被加载时,数据库就生成了一个名为 pg_stat_statements
的视图,有以下列:
- userid
- dbid
- queryid
- query
- calls
- total_time
- min_time
- max_time
- mean_time
- stddev_time
- rows
- shared_blks_hit
- shared_blks_read
- shared_blks_dirtied
- shared_blks_written
- local_blks_hit
- local_blks_read
- local_blks_dirtied
- local_blks_written
- temp_blks_read
- temp_blks_written
- blk_read_time
- blk_write_time
数据库配置
shared_preload_libraries = 'pg_stat_statements'
pg_stat_statements.max = 1000
pg_stat_statements.track = all
清除目前的 pg_stat_statements 的统计信息
SELECT pg_stat_statements_reset();
查询最耗时的 sql 语句
SELECT
query,
calls,
total_time,
rows,
100.0 * shared_blks_hit / nullif(shared_blks_hit + shared_blks_read, 0) AS hit_percent
FROM pg_stat_statements
ORDER BY total_time DESC
LIMIT 5;