가장 비용이 큰 쿼리 찾기(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을 실행하기 전에는 아무것도 수집하지 않는다. 값은 마지막 reset 이후 누적이다. mean_ms 대비 stddev_ms가 높으면 호출 간 계획이나 데이터 분포가 달라진다는 뜻이다. mean_plan_time은 pg_stat_statements.track_planning = on(기본 off, 활성화 시 오버헤드 추가)일 때만 채워진다. 다른 사용자의 쿼리 텍스트를 보려면 superuser 또는 pg_read_all_stats 롤이 필요하다.