PostgreSQL · Performance diagnosis · DBA-016
How to Find Long-Running Queries and Transactions in PostgreSQL
Identify statements running longer than expected and transactions left open long after their last query ended.
The short answer
Use pg_stat_activity to check two different clocks: how long an active query has been running, and how long its transaction has been open. Filter by thresholds that fit your workload, then investigate long-lived idle in transaction sessions separately from genuinely long-running statements.
The SQL diagnostic
Run this read-only query against the PostgreSQL environment you are investigating. Interpret the results in the context of your workload and privileges.
SELECT
pid,
usename,
application_name,
state,
CASE WHEN state = 'active'
THEN now() - query_start END AS active_query_age,
now() - xact_start AS transaction_age,
left(query, 120) AS query_preview
FROM pg_stat_activity
WHERE backend_type = 'client backend'
AND (
(state = 'active'
AND query_start < now() - interval '5 minutes')
OR
(xact_start IS NOT NULL
AND xact_start < now() - interval '15 minutes')
)
ORDER BY xact_start NULLS LAST,
query_start NULLS LAST;Adapted from DBA-016. Query age is shown only for active statements, while transaction age is based on xact_start.
How to read the results
idle in transaction session can keep a transaction open without executing a statement.The example uses five-minute query and fifteen-minute transaction thresholds from the book’s troubleshooting approach. Those are starting thresholds, not universal danger limits. Analytical jobs and maintenance operations can legitimately run longer than short OLTP transactions.
Unlike a query-duration report, this includes a long-open transaction even when its session is currently idle in transaction.
What to check next
- Separate slow statements from forgotten transactions. An active query may be working or waiting; an idle transaction is a session waiting for the next client command.
- Check for blockers. Use the blocking-session report if other operations are hanging. Avoid interpreting elapsed time alone as proof of lock blocking.
- Find the application owner. Trace the application name and connection pool settings before treating a session as abandoned.
- Correct the cause. Look for transaction boundaries and application error paths that fail to commit or roll back.
Related DBA tasks
Continue the investigation with these recipes from SQL Recipes for DBAs: DBA-015 (active sessions), DBA-017 (cancel or terminate), DBA-018 (blocking sessions), and DBA-037 (vacuum and maintenance).
Continue learning · Baldwin Apps
More practical solutions in SQL Recipes for DBAs
Find engine-specific recipes for sessions, locks, performance, permissions, backups, maintenance, and troubleshooting. Explore the book and its existing companion materials.