pg_stat_activity — Complete Guide
pg_stat_activity — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of PostgreSQL Tutorial on Toolliyo Academy.
On this page
PostgreSQL Tutorial · Lesson 81 of 100
pg_stat_activity
SQL ✓ → Advanced
Advanced · 2 — Production · ~10 min · PostgreSQL — Monitoring & Troubleshooting
What is this?
pg_stat_activity is a live view of server processes — running queries, wait events, client IP, transaction age, and state idle in transaction.
Why should you care?
PostgresVerse checkout slow — on-call filters pg_stat_activity for long running queries blocking pool.
See it live — copy this example
Run in pgAdmin or psql.
SELECT pid, usename, datname, state, wait_event_type, wait_event,
now() - query_start AS runtime, left(query, 80) AS query_snip
FROM pg_stat_activity
WHERE datname = 'PostgresVerse'
AND state <> 'idle'
ORDER BY runtime DESC;
What happened?
- Lists non-idle backends on PostgresVerse sorted by runtime.
- wait_event shows IO, Lock, or Client waits.
- query_snip helps identify culprit SQL.
Practice next
- Run query during normal load.
- Start pg_sleep(30) in another session; find it in activity view.
- Note idle in transaction session with old xact_start.
- Filter application_name from JDBC pool.
- Join pg_locks on pid for blocked/blocking tree.
Remember
First stop for who is running what. wait_event_type diagnoses waits not just slow CPU. Cancel vs terminate — cancel is gentler.
PostgresVerse incident triage
P95 spike; on-call finds analytics query at 400s runtime and cancels it.
Outcome: Checkout recovers in 2 minutes without restart.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!