Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 139/ 160
07. Indexing, Query Optimization & Performance Tuning

Identifying Slow Queries (pg_stat_statements & Slow Query Logs)

Find the worst offenders using pg_stat_statements and slow query logs.

Intermediatepg_stat_statements · Slow Logs3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

Top queries by total timeQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  round(total_exec_time) AS total_ms,3  calls,4  round(mean_exec_time, 2) AS mean_ms,5  rows,6  left(query, 80) AS query7FROM8  pg_stat_statements9ORDER BY10  total_exec_time DESC11LIMIT12  10;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/12
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative pg_stat_statements report3 sample rows
Representative pg_stat_statements report
total_mscallsmean_msrowsquery
8420001250673.615000SELECT * FROM orders WHERE status = $1 ORDER BY created_at DESC
315000420007.542000SELECT id FROM users WHERE email = $1
178000180988.89126000SELECT 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.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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.

Logging slow statements and their plansQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1ALTER SYSTEM2SET3  log_min_duration_statement = '500ms';
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/3
query.sql
1SELECT2  pg_reload_conf();
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/2
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative configuration result
ALTER SYSTEM pg_reload_conf -------------- t

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.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Setup

Turn on measurement

Enable pg_stat_statements and set a sensible log_min_duration_statement so you have data before problems happen.

SQL at this step
1CREATE EXTENSION pg_stat_statements;
What to watch at this step
Before
the incident
Tip: use ← → to move between steps

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

pg_stat_statements
Best for: Finding which query shapes cost the most overall

Strengths: Aggregated across all calls; shows calls, total and mean time.

Watch out: No individual parameter values or plans.

Slow query log
Best for: Capturing individual slow executions with real parameters

Strengths: Lets you reproduce a specific slow call.

Watch out: Misses fast-but-frequent queries entirely.

auto_explain
Best for: Seeing the plan actually used for slow statements

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?
Interview tip: Lead with "rank by total time, not by slowest query" and give the 8 ms × 4 million example. Then describe the measure, explain, fix, re-measure loop.

Knowledge check

Loading quiz

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.

Open SQL Practice →SQL interview Q&A
Previous topic
Connection Pooling (PgBouncer) & Statement Timeouts
Next topic
End-to-End Query Tuning Case Studies (Turning a 30s Query into 30ms)