pg_stat_statements — Complete Guide
pg_stat_statements — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of PostgreSQL Tutorial on Toolliyo Academy.
On this page
PostgreSQL Tutorial · Lesson 82 of 100
pg_stat_statements
SQL ✓ → Advanced
Advanced · 2 — Production · ~10 min · PostgreSQL — Monitoring & Troubleshooting
What is this?
pg_stat_statements extension aggregates execution stats per normalized query — calls, total time, mean time, rows, shared buffer hits — across all sessions.
Why should you care?
PostgresVerse optimization sprint ranks queries by total_exec_time to fix what actually hurts users not what looks scary in one EXPLAIN.
See it live — copy this example
Run in pgAdmin or psql.
SELECT calls,
round(total_exec_time::numeric, 2) AS total_ms,
round(mean_exec_time::numeric, 2) AS mean_ms,
rows,
left(query, 100) AS q
FROM pg_stat_statements
WHERE dbid = (SELECT oid FROM pg_database WHERE datname = 'PostgresVerse')
ORDER BY total_exec_time DESC
LIMIT 10;
What happened?
- Top total_exec_time queries consumed most cluster time cumulatively.
- mean_ms catches fast-but-frequent.
- Reset stats after deploy to measure regression.
Practice next
- CREATE EXTENSION pg_stat_statements if needed.
- Generate traffic or run app suite.
- Query top 10 by total and by mean.
- Filter query ILIKE '%orders%' for domain focus.
- Compare shared_blks_hit vs read for cache efficiency.
Remember
Normalized query text groups prepared statement variants. total vs mean tells different optimization stories. Reset after major release for clean comparison.
PostgresVerse query top 10
Weekly review finds order history query 40% of DB time; index added.
Outcome: Cloud RDS CPU drops one size tier saving monthly cost.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!