PostgreSQL安装pg_stat_statements模块开启慢查询统计

安装pg_stat_statements模块开启慢查询统计

# 需要安装相同版本的contrib包
yum install -y postgresql-contrib.x86_64

# 修改配置文件
vim /var/lib/pgsql/data/postgresql.conf
# 当需要跟踪SQL语句或者慢语句,得需要设置以下参数:
log_statement = all #需设置跟踪所有语句,否则只能跟踪出错信息
log_min_duration_statement = 5000 #milliseconds,记录执行5秒及以上的语句

shared_preload_libraries = 'pg_stat_statements' # (change requires restart)
#以下配置pg_stat_statements采样参数
pg_stat_statements.max = 10000
## 在pg_stat_statements中最多保留多少条统计信息,通过LRU算法,覆盖老的记录。
pg_stat_statements.track = all
## all - (所有SQL包括函数内嵌套的SQL), top - 直接执行的SQL(函数内的sql不被跟踪), none - (不跟踪)
pg_stat_statements.track_utility = off
## 是否跟踪非DML语句 (例如DDL,DCL),on表示跟踪, off表示不跟踪
pg_stat_statements.save = on


# 重启服务
su - postgres
pg_ctl -D /var/lib/pgsql/data reload


# 创建 extension
# 由于pg_stat_statements针对的是数据库级别,所以需要首先进入指定数据库
psql
\l
\c test01
create extension pg_stat_statements;

\df

查询慢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 calls,total_time DESC LIMIT 5;

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 calls,total_time DESC LIMIT 5;

参考文档