Identifying Slow Queries (pg_stat_statements & Slow Query Logs)
Find the worst offenders using pg_stat_statements and slow query logs.
In plain words
Keep a list of every kind of query and how much time it used in total, then fix the ones at the top of the list.
Think of it like…
Reducing a household's spending: the most expensive single purchase (a new sofa) matters less than the small daily coffee bought 700 times a year. Look at the totals before deciding what to cut.
Where you’ve seen it
pg_stat_statements shows a lookup SELECT … FROM sessions WHERE token = $1 averaging 8 ms but called 4 million times a day, using 9 hours of database time daily: more than every report combined. An index on token cuts it to 0.1 ms and frees most of the database's capacity.
Words you’ll hear
- pg_stat_statements
- Per-query-shape statistics: calls, total_exec_time, mean_exec_time, rows, shared_blks_hit/read.
- Normalized query
- The query with literals replaced by $1, $2, so similar calls are grouped together.
- log_min_duration_statement
- Logs every statement slower than the given duration.
- auto_explain
- Logs the execution plan of statements slower than a threshold.
Visual diagram
Theory & example queries
Using pg_stat_statements
Enable it by adding pg_stat_statements to shared_preload_libraries and running CREATE EXTENSION pg_stat_statements; (managed services usually have it available). Then query the view, ordering by total_exec_time to find the biggest consumers, by mean_exec_time for the slowest per call, and by calls for chatty patterns like N+1 queries.
Look at rows per call and buffer usage too: a query reading millions of shared blocks to return 10 rows is a strong hint of a missing index. The view resets on restart or when you call pg_stat_statements_reset(), which is useful for measuring the effect of a fix over a fresh period.
SELECT round(total_exec_time) AS total_ms, calls, round(mean_exec_time, 2) AS mean_ms, rows, left(query, 80) AS queryFROM pg_stat_statementsORDER BY total_exec_time DESCLIMIT 10;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Representative pg_stat_statements report3 sample rows
| total_ms | calls | mean_ms | rows | query |
|---|---|---|---|---|
| 842000 | 1250 | 673.6 | 15000 | SELECT * FROM orders WHERE status = $1 ORDER BY created_at DESC |
| 315000 | 42000 | 7.5 | 42000 | SELECT id FROM users WHERE email = $1 |
| 178000 | 180 | 988.89 | 126000 | SELECT customer_id, SUM(amount) FROM orders GROUP BY customer_id |
Note: Illustrative normalized statements and counters. Actual totals, means, row counts and query text depend on PostgreSQL version and workload since the statistics view was reset.
Key takeaway: Sort by total time first: that's where capacity goes.
Slow logs, plans and the tuning loop
log_min_duration_statement = '500ms' writes every statement slower than 500 ms to the log, with its actual parameters, which helps reproduce a specific slow call. auto_explain (with auto_explain.log_min_duration) also logs the plan that was used, which matters because a plan can differ for different parameter values.
The loop is: find the top queries by total time, run EXPLAIN (ANALYZE, BUFFERS) on a representative call, fix the cause (an index, a rewrite, fresh statistics, or fewer calls by fixing an N+1 pattern in the application), then confirm in pg_stat_statements that total time dropped. In MySQL, the slow query log with long_query_time and the sys schema's statement summaries play the same role.
ALTER SYSTEMSET log_min_duration_statement = '500ms';PostgreSQL is the lesson baseline unless noted otherwise.
Identify the table or database object the statement will modify.
SELECT pg_reload_conf();PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Representative configuration result
Note: Configuration changes require suitable privileges. pg_reload_conf() returning true confirms a reload request, but some preload settings apply only after a server restart or a new session.
and in postgresql.conf: session_preload_libraries = 'auto_explain', auto_explain.log_min_duration = '1s', then
Key takeaway: Find with statistics, explain with plans, fix, then measure again.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Turn on measurement
Enable pg_stat_statements and set a sensible log_min_duration_statement so you have data before problems happen.
CREATE EXTENSION pg_stat_statements;When to use it & trade-offs
What it is
Before tuning anything, find which queries actually cost the most. In PostgreSQL, the pg_stat_statements extension groups queries by shape (with literal values removed) and records how often each ran, its total and mean time, and rows and buffers. Slow query logs (log_min_duration_statement in PostgreSQL, slow_query_log in MySQL) record individual executions above a threshold, and auto_explain logs their plans.
Why it matters: The slowest single query is often not the biggest problem: a 5 ms query run a million times an hour costs far more than a 3-second report run twice a day. Sorting by total time tells you where tuning pays off. Interviewers ask "the database is slow, where do you start?", and this is the answer.
When to reach for it
- Starting any performance investigation
- Finding N+1 query patterns from the application
- Measuring the effect of index and query changes
When to avoid or be careful
- Tuning whatever query someone complained about without checking totals
- Relying only on the slow log, which hides frequent cheap queries
- Leaving auto_explain with full ANALYZE timing on a busy system
pg_stat_statements vs slow query log vs auto_explain
Strengths: Aggregated across all calls; shows calls, total and mean time.
Watch out: No individual parameter values or plans.
Strengths: Lets you reproduce a specific slow call.
Watch out: Misses fast-but-frequent queries entirely.
Strengths: Catches plan differences for specific parameter values.
Watch out: Extra logging overhead, especially with ANALYZE enabled.
Interview signals & numbers to know
When this topic comes up
- “The database CPU is at 90%, where do you start?”
- “Which queries should we optimise?”
- N+1 queries
- pg_stat_statements
- Slow query log
Benchmarks & rules of thumb
- calls × mean
- = total time
- 500 ms
- a common log_min_duration_statement starting point
- Top 10
- queries usually account for most of the load
Common mistakes & follow-ups
Common interview mistakes
- Optimising the slowest single query while a fast one run millions of times uses most of the database.
- Reading pg_stat_statements after a restart and assuming the numbers cover all time.
- Testing a fix with different parameters from the slow calls, so the plan isn't the same.
Likely interviewer follow-ups
- The database is slow. How do you find out which queries to fix?
- Why sort by total time rather than mean time?
- How would you spot an N+1 query pattern from database statistics?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Identifying Slow Queries (pg_stat_statements & Slow Query Logs) with hands-on SQL practice and interview Q&A.