PostgreSQL exposes rich real-time and cumulative diagnostics through its built-in pg_stat_* system views and the pg_stat_statements extension.

Active sessions & blocking queries (pg_stat_activity)#

Find currently running queries and what they are waiting on:

SELECT
  pid,
  usename,
  datname,
  state,
  wait_event_type,
  wait_event,
  now() - query_start AS duration,
  left(query, 100) AS query
FROM pg_stat_activity
WHERE state <> 'idle'
  AND pid <> pg_backend_pid()
ORDER BY duration DESC;

Find blocked sessions and who is blocking them:

SELECT
  blocked.pid AS blocked_pid,
  blocked.usename AS blocked_user,
  pg_blocking_pids(blocked.pid) AS blocking_pids,
  now() - blocked.query_start AS wait_duration,
  left(blocked.query, 80) AS blocked_query
FROM pg_stat_activity blocked
WHERE cardinality(pg_blocking_pids(blocked.pid)) > 0;

Table access patterns (pg_stat_all_tables)#

Identify tables with heavy sequential scans or high write churn:

SELECT
  schemaname || '.' || relname AS table_name,
  seq_scan,
  idx_scan,
  n_tup_ins,
  n_tup_upd,
  n_tup_del,
  n_dead_tup
FROM pg_stat_user_tables
ORDER BY seq_scan DESC
LIMIT 15;

Unused or low-value indexes (pg_stat_all_indexes)#

Find large indexes that are never scanned (candidates for review before dropping):

SELECT
  schemaname || '.' || relname AS table_name,
  indexrelname AS index_name,
  idx_scan,
  pg_size_pretty(pg_relation_size(indexrelid)) AS index_size
FROM pg_stat_user_indexes
WHERE idx_scan = 0
ORDER BY pg_relation_size(indexrelid) DESC
LIMIT 15;

Checkpointer & background writer#

Monitor checkpoint frequency and buffer flushes (in PostgreSQL 17+, checkpoint stats moved to pg_stat_checkpointer):

-- PostgreSQL 17+
SELECT num_timed, num_requested, write_time, sync_time, buffers_written
FROM pg_stat_checkpointer;

SELECT buffers_clean, maxwritten_clean, buffers_alloc
FROM pg_stat_bgwriter;

A high ratio of num_requested vs num_timed checkpoints indicates max_wal_size is too small for your write workload.

Query performance (pg_stat_statements)#

Enable pg_stat_statements in postgresql.conf (requires a restart):

shared_preload_libraries = 'pg_stat_statements'
pg_stat_statements.track = all

Then create the extension in your database:

CREATE EXTENSION IF NOT EXISTS pg_stat_statements;

Find the top 10 queries by total execution time:

SELECT
  calls,
  round(total_exec_time::numeric, 1) AS total_ms,
  round(mean_exec_time::numeric, 2) AS mean_ms,
  rows,
  left(query, 100) AS query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;