How do you find slow queries in PostgreSQL?
IntermediateHands-onPostgreSQL
Answer
Short answer
Log slow statements with log_min_duration_statement, see what's running now in pg_stat_activity, find the most expensive queries over time with the pg_stat_statements extension, and analyse them with EXPLAIN (ANALYZE, BUFFERS). On RDS/Azure, use Performance Insights / Query Store.
Log slow queries
ALTER SYSTEM SET log_min_duration_statement = '500ms';
SELECT pg_reload_conf();
Running now
SELECT pid, now() - query_start AS runtime, state, wait_event_type, left(query, 80)
FROM pg_stat_activity WHERE state <> 'idle' ORDER BY runtime DESC;
SELECT pg_cancel_backend(12345); -- cancel the query
SELECT pg_terminate_backend(12345); -- kill the session
Top queries overall
CREATE EXTENSION IF NOT EXISTS pg_stat_statements; -- needs shared_preload_libraries
SELECT calls, round(total_exec_time) AS total_ms, round(mean_exec_time) AS avg_ms, left(query, 80)
FROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 10;
Analyse one
EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM orders WHERE customer_id = 42 ORDER BY created_at DESC LIMIT 20;
Look for Seq Scan on big tables, estimated vs actual row counts far apart (stale stats → ANALYZE), and large sorts spilling to disk.
What to say in the interview
"log_min_duration_statement for the slow log, pg_stat_activity for live queries, pg_stat_statements to rank queries by total time, then EXPLAIN ANALYZE with BUFFERS to see seq scans or bad estimates. Fixes are usually an index, fresh statistics or a query rewrite."
More on PostgreSQL
How do you set up PostgreSQL and log in with psql?BeginnerHow do you create a database, tables, users and query data in PostgreSQL?BeginnerHow do you back up and restore a PostgreSQL database?BeginnerWhat is PostgreSQL and why is it so popular?BeginnerHow is PostgreSQL organised: cluster, database, schema and table?BeginnerHow do you connect to PostgreSQL from the command line?Beginner