Skip to content

Commit 8eac57a

Browse files
Add diagnostic script to show currently running queries and their status
1 parent 3e1f381 commit 8eac57a

1 file changed

Lines changed: 39 additions & 0 deletions

File tree

activity.sql

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/*
2+
* Script: sql/diagnostics/activity.sql
3+
*
4+
* Purpose: Shows currently running queries and their status.
5+
*
6+
* Description:
7+
* This query provides a snapshot of `pg_stat_activity`, filtered to show only
8+
* active queries. It is a fundamental tool for understanding the current
9+
* workload on the database. It excludes idle connections and the current
10+
* session running this tool.
11+
*
12+
* Red Flags:
13+
* - High `runtime`: Queries that have been running for a long time are often problematic.
14+
* - `wait_event` is not NULL: The query is waiting on a resource (e.g., 'Lock', 'IO'). This is a key indicator for bottlenecks.
15+
* - `state = 'active'` but `wait_event` is NULL: The query is likely CPU-bound.
16+
*
17+
* Interpretation:
18+
* - The `runtime` column shows how long the current query has been executing.
19+
* - `wait_event_type` and `wait_event` tell you exactly what a query is waiting for, if anything.
20+
* - The `query` column shows the text of the running query, truncated for readability.
21+
*
22+
* Safety:
23+
* This script is read-only. It queries the `pg_stat_activity` view, which is
24+
* a memory-based view and is extremely fast to access. The `statement_timeout`
25+
* set by `pgtools.sh` provides an additional safety guarantee.
26+
*/
27+
SELECT
28+
pid,
29+
usename,
30+
application_name,
31+
state,
32+
wait_event_type,
33+
wait_event,
34+
now() - query_start AS runtime,
35+
left(query, 200) AS query
36+
FROM pg_stat_activity
37+
WHERE state <> 'idle'
38+
AND pid <> pg_backend_pid()
39+
ORDER BY query_start;

0 commit comments

Comments
 (0)