🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Query Statistics & Execution Plans — EXPLAIN, pg_stat_statements, Performance Monitoring

Advanced SQLPerformance⭐ Premium

Query Statistics & Execution Plans

Advanced SQL

Monitor & Optimize

Understanding how the database executes your queries is the foundation of performance optimization. EXPLAIN ANALYZE reveals the execution plan, pg_stat_statements tracks query performance over time, and system views expose locks, connections, and vacuum status.

  • EXPLAIN ANALYZE — See actual execution times and row counts
  • pg_stat_statements — Track slow queries and cache hit ratios
  • Index Usage — Find unused indexes and missing indexes
  • Lock Monitoring — Detect blocking queries and deadlocks

The difference between a 1ms query and a 10s query is usually an execution plan issue — and EXPLAIN is how you find it.


EXPLAIN ANALYZE Deep Dive

-- Full execution plan analysis
EXPLAIN (
  ANALYZE, BUFFERS, COSTS, TIMING, VERBOSE, FORMAT JSON
)
SELECT
  d.department_name,
  COUNT(e.employee_id) AS emp_count
FROM departments d
INNER JOIN employees e ON d.department_id = e.department_id
GROUP BY d.department_name;

Key EXPLAIN Output Sections

SectionWhat It Shows
CostEstimated startup/total cost (abstract units)
RowsEstimated vs actual row counts
TimeActual execution time (ms)
Buffersshared hits (cache) vs reads (disk)
Planning TimeTime to generate the plan
Execution TimeTotal time including all nodes

ℹ️

Key Insight: The Buffers option shows shared hits (from cache), shared reads (from disk), and temp usage. High shared reads indicates the query is I/O bound — consider adding indexes or increasing shared_buffers.

Read the plan in a fixed order: planning time, then node types from the outermost line inward, then actual rows against estimated rows. A row estimate that is off by a factor of one thousand is the signal that stale statistics or a skewed distribution sent the planner down the wrong join order, and the remedy is ANALYZE or a higher statistics target, not a query rewrite. Compare actual loops with total time too — a node costing 50 ms once is cheap, while a node costing 2 ms across 40000 loops is the real expense. Keep the JSON format output when a plan becomes a recurring argument between releases, because it diffs cleanly.


Execution Plan Operators

Seq ScanFull table scanSlow for large tablesFix: Add indexIndex ScanUses index for lookupFast for selective queriesGood for point lookupsHash JoinBuilds hash tableGood for large joinsCheck build sideNested LoopRow-by-row joinGood for small setsBad for large tablesSortIn-memory or disk sortExpensive for large dataFix: Add ORDER BY indexHash AggregateGROUP BY via hash tableFast for GROUP BYMemory: work_memMerge JoinMerge sorted inputsGood for sorted dataNeeds sorted inputsMaterializeBuffer resultsUsed for CTEsCan spill to disk

Those boxes form a decision tree in practice. A nested loop wins when the outer side holds a few hundred rows and the inner side has an index; once the outer side reaches a million rows the same plan collapses, because the inner index is probed a million times. Hash joins require the build side to fit in work_mem, and a hash join that spills shows up as a temporary file in the buffers line — raise memory or pre-filter the build side. Merge joins want sorted inputs, so an index that already supplies the sort order removes a separate sort node entirely, which is why the same join can appear in three shapes across three releases of the same query.


pg_stat_statements

-- Enable pg_stat_statements
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;

-- Top queries by total time
SELECT query, calls, total_time, mean_time, rows
FROM pg_stat_statements
ORDER BY total_time DESC
LIMIT 10;

-- Queries with highest I/O (low cache hit ratio)
SELECT
  query,
  shared_blks_read,
  shared_blks_hit,
  ROUND(shared_blks_hit * 100.0 /
    NULLIF(shared_blks_hit + shared_blks_read, 0), 2) AS cache_hit_ratio
FROM pg_stat_statements
ORDER BY shared_blks_read DESC
LIMIT 10;

pg_stat_statements normalises statements by replacing literals with placeholders, so WHERE id = 41 and WHERE id = 987 accumulate under one entry — that is what makes the totals useful, and what turns a query built by string concatenation into thousands of unrelated entries that never reach the top of the list. The counters survive until the first pg_stat_statements_reset() after a deploy, so snapshot the view before restarting. Two columns drive triage: total_time finds the statements costing the most in aggregate, while mean_time paired with a high calls count finds the cheap-but-constant queries that a cache removes far more easily than a rewrite does.


Index Usage Statistics

-- Check index usage
SELECT schemaname, tablename, indexname, idx_scan, idx_tup_read, idx_tup_fetch
FROM pg_stat_user_indexes
WHERE schemaname = 'public'
ORDER BY idx_scan DESC;

-- Identify unused indexes (candidates for removal)
SELECT
  indexrelname, idx_scan,
  pg_size_pretty(pg_relation_size(indexrelid)) AS size
FROM pg_stat_user_indexes
WHERE idx_scan = 0 AND indexrelname NOT LIKE '%pkey%'
ORDER BY pg_relation_size(indexrelid) DESC;

Zero scans is a necessary condition for dropping an index, not a sufficient one. A freshly created index reads zero until traffic arrives, a streaming standby applies writes but never runs the reporting query that uses it, and a quarterly report looks idle for ninety days out of ninety-one. Before dropping, confirm the counter covers the busiest cycle you expect, check that no view or function depends on the index, and weigh the write cost you would recover: every index on a table adds page writes and WAL for each modified row. A 4 GB index saving 200 ms a week is a bad trade; a 40 MB one almost never is.


Table Statistics & Bloat

-- Table bloat analysis
SELECT
  schemaname, tablename,
  pg_size_pretty(pg_total_relation_size(schemaname||'.'||tablename)) AS total_size,
  pg_size_pretty(pg_relation_size(schemaname||'.'||tablename)) AS table_size,
  pg_size_pretty(pg_indexes_size(schemaname||'.'||tablename)) AS index_size,
  n_live_tup, n_dead_tup,
  ROUND(n_dead_tup * 100.0 / NULLIF(n_live_tup + n_dead_tup, 0), 2) AS dead_pct
FROM pg_stat_user_tables
ORDER BY pg_total_relation_size(schemaname||'.'||tablename) DESC;

⚠️

Warning: High dead tuple percentage (>10%) indicates vacuum is falling behind. Run VACUUM VERBOSE tablename; manually or tune autovacuum settings.

Dead tuples are not bloat by themselves, they are vacuum falling behind, and each one forces the executor to check an old version against the visibility map. The first lever is lowering autovacuum_vacuum_scale_factor on large tables — 0.01 instead of the 0.2 default — so cleanup triggers at one percent churn rather than twenty. VACUUM VERBOSE reports how many pages were removed, while VACUUM (FULL) rewrites the table under an exclusive lock and belongs in a maintenance window rather than in a reflex. Watch n_mod_since_analyze alongside the dead-tuple count: stale row estimates degrade plans long before bloat becomes visible in I/O.


Lock Monitoring

-- Check current locks (blocking queries)
SELECT
  l.pid, l.mode, l.granted, a.query, a.query_start,
  NOW() - a.query_start AS duration
FROM pg_locks l
INNER JOIN pg_stat_activity a ON l.pid = a.pid
WHERE NOT l.granted
ORDER BY a.query_start;

-- Check for long-running queries
SELECT pid, query, state, query_start,
  NOW() - query_start AS duration
FROM pg_stat_activity
WHERE state = 'active'
  AND query_start < NOW() - INTERVAL '5 minutes'
ORDER BY query_start;

Blocked work appears in pg_locks as a waiting row and in pg_stat_activity as a query whose wait_event_type reads Lock. The useful triage query returns the blocking PID and the blocked PID together, because the blocker's statement is normally the whole story: a long migration, a transaction left open by an application server, or a FOR UPDATE held across a user think. Setting idle_in_transaction_session_timeout turns a forgotten transaction into a logged error instead of a night of held row locks. Deadlocks are a separate case — one side aborts and the log names the victim — so a consistently recurring victim points at lock acquisition order rather than at slow SQL.


Vacuum and Analyze

-- Manual vacuum with statistics update
VACUUM (ANALYZE, VERBOSE) employees;

-- Check vacuum progress
SELECT relname, phase, heap_blks_total, heap_blks_scanned, heap_blks_vacuumed
FROM pg_stat_progress_vacuum;

-- Update table statistics
ANALYZE employees;

-- Increase statistics target for important columns
ALTER TABLE employees ALTER COLUMN salary SET STATISTICS 1000;

ANALYZE samples values per column and stores histograms plus most-common-value lists, which the planner converts into row estimates. The per-column STATISTICS target raises how many sample values are kept for that column, so raise it on the columns used in range predicates and join keys rather than globally — extra targets cost time and memory on every run. Expressions such as LOWER(email) need CREATE STATISTICS on the expression, otherwise the planner never sees the correlation between the raw column and the index predicate. When plans flip after a deploy, compare pg_stats rows — null fractions, distinct counts, most common values — before touching any planner cost constant.


BigQuery Execution Details

-- BigQuery job statistics
SELECT
  job_id, creation_time, end_time,
  TIMESTAMP_DIFF(end_time, creation_time, SECOND) AS duration_seconds,
  total_bytes_processed,
  ROUND(total_bytes_processed / POWER(1024, 3), 2) AS processed_gb,
  cache_hit
FROM `project.dataset.INFORMATION_SCHEMA.JOBS`
WHERE query LIKE '%SELECT%'
ORDER BY creation_time DESC LIMIT 10;

The BigQuery job view plays the role pg_stat_statements plays for a server: every statement lands there with bytes processed, slot milliseconds and cache status. Sorting by total_bytes_processed surfaces the genuinely expensive scans, and cache_hit separates a heavy query from one that is heavy only on the first run of the day. Grouping on parent_job_id reassembles the fragments of a scripted job into one cost figure, and keeping a creation_time filter inside the query stops the metadata scan itself from becoming the most expensive statement in the account.


Quiz: Test Your Knowledge


Follow-Up Questions

  1. How do you interpret a query plan's cost estimates?
  2. What's the difference between a bitmap scan and an index scan?
  3. How do you identify queries that need optimization?
  4. Explain the impact of table statistics on query planning.
  5. How do you monitor query performance in real-time?

Common Mistakes

Reading EXPLAIN without ANALYZE and trusting the estimated row counts

Fix: Run EXPLAIN (ANALYZE, BUFFERS) on a representative data shape and compare actual rows against estimates

Dropping every index that shows zero scans

Fix: Confirm the observation window covers your busiest cycle, check dependencies, and weigh the write cost you would reclaim

Tuning autovacuum on dead tuples alone

Fix: Track n_mod_since_analyze as well, since stale statistics degrade plans before bloat is visible

Investigating a slow query before identifying who blocks it

Fix: Check pg_locks and wait_event_type first; a blocked statement is often waiting rather than slow

Key Takeaways

  • EXPLAIN ANALYZE — Always use BUFFERS to see I/O; compare estimated vs actual rows
  • pg_stat_statements — Track slow queries, cache hit ratios, and I/O patterns
  • Unused indexes — Remove indexes with 0 scans to improve write performance
  • Dead tuples — Monitor n_dead_tup; >10% means vacuum is behind
  • Lock monitoring — pg_locks + pg_stat_activity to detect blocking queries
  • ANALYZE — Update statistics so the optimizer picks the right plan
🔒

Premium Content

Query Statistics & Execution Plans — EXPLAIN, pg_stat_statements, Performance Monitoring

You've previewed the first section. Unlock this full lesson and 900+ advanced tutorials with a Premium plan.

🎯End-to-end Projects
💼Interview Prep
📜Certificates
🤝Community Access

Already a member? Log in

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-15

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Advertisement