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.
Code
-- 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
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.
FAQ
- What objects does the SQL involve?
- The references are `pg_stat_statements`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.