pg stat statements Top Query Stats

Rank real workload queries by total time with pg_stat_statements: enable the extension once, then read normalized call counts and timing.

SqlConfig Management

Code

snippet
-- pg_stat_statements:按规范化查询聚合真实执行统计
-- 前置:shared_preload_libraries 含 'pg_stat_statements'(重启生效)
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;

-- 最耗时的查询排行:总时间、调用次数、平均时间
SELECT
    queryid,
    calls,
    -- ROUND 保证报告里出现的是两位小数,而不是长尾浮点
    ROUND(total_exec_time::numeric, 2)          AS total_ms,
    ROUND(mean_exec_time::numeric, 2)           AS avg_ms,
    rows,
    LEFT(query, 60)                             AS query_head
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;

-- 高调用次数排行:识别 N+1 或热循环
SELECT calls, ROUND(mean_exec_time::numeric, 3) AS avg_ms, LEFT(query, 60) AS query_head
FROM pg_stat_statements
ORDER BY calls DESC
LIMIT 10;

-- 重置统计:在变更前后各拍一次快照做对比
SELECT pg_stat_statements_reset();

How the snippet works

Several statements share this file — SELECT / CREATE, with pg_stat_statements among the objects involved.

What the statements actually assemble: an ORDER BY that fixes the output order; a row cap (LIMIT) bounding the result size.

Applying it

Point it at the pg_stat_statements table — the LIMIT keeps the probe cheap while you tune the predicates.

Statements that matter

SELECT
queryid,
calls,
ROUND(total_exec_time::numeric, 2)          AS total_ms,
ROUND(mean_exec_time::numeric, 2)           AS avg_ms,
rows,
LEFT(query, 60)                             AS query_head
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;
SELECT calls, ROUND(mean_exec_time::numeric, 3) AS avg_ms, LEFT(query, 60) AS query_head
FROM pg_stat_statements
ORDER BY calls DESC
LIMIT 10;
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;

Interactive Tools for This Topic

FAQ

What objects does the SQL involve?
The references are `pg_stat_statements`.