Identifying and Fixing Slow Queries
Use pg_stat_statements, log_min_duration_statement, and EXPLAIN to find slow queries and apply targeted fixes.
Step 1: Find the Slow Ones
Don't optimise blind. Use:
pg_stat_statements— top queries by total timelog_min_duration_statement— log queries above a threshold- pgBadger — pretty reports from logs
pg_stat_statements Setup
Enable the extension and configure shared_preload_libraries:
-- postgresql.conf
shared_preload_libraries = 'pg_stat_statements'
-- After restart:
CREATE EXTENSION pg_stat_statements;All lessons in this course
- Reading EXPLAIN and EXPLAIN ANALYZE
- Sequential Scans vs Index Scans
- Hash Join vs Merge Join vs Nested Loop
- Identifying and Fixing Slow Queries