Query Analysis in PostgreSQL
From the PostgreSQL Advanced Features cheat sheet ยท Indexes & Performance ยท verified Jul 2026
Query Analysis
Analyze and optimize query performance
sql
-- Explain query plan
EXPLAIN SELECT * FROM users WHERE email = 'john@example.com';
-- Explain with execution stats
EXPLAIN ANALYZE SELECT * FROM orders WHERE user_id = 123;
-- Verbose explain with buffers
EXPLAIN (ANALYZE, BUFFERS, VERBOSE)
SELECT * FROM large_table WHERE status = 'active';
-- Check index usage
SELECT
schemaname,
tablename,
indexname,
idx_scan,
idx_tup_read,
idx_tup_fetch
FROM pg_stat_user_indexes
ORDER BY idx_scan;
-- DETAILED_TAB:
-- Find missing indexes
SELECT
schemaname,
tablename,
attname,
n_distinct,
correlation
FROM pg_stats
WHERE schemaname = 'public'
AND n_distinct > 100
AND correlation < 0.1
ORDER BY n_distinct DESC;
-- Query cache hit ratio
SELECT
sum(heap_blks_hit) / (sum(heap_blks_hit) + sum(heap_blks_read)) as cache_hit_ratio
FROM pg_statio_user_tables;
-- Slow query log (pg_stat_statements)
SELECT
query,
mean_exec_time,
calls,
total_exec_time
FROM pg_stat_statements
ORDER BY mean_exec_time DESC
LIMIT 10;๐ก EXPLAIN ANALYZE shows actual execution times
๐ Look for Seq Scan on large tables
โก Cache hit ratio should be > 95%
๐ข Essential for performance tuning
๐ Related: pg_stat_statements extension
performanceanalysis