From af7cf4a0a0ac0d59eca65025f3a833a6b3144677 Mon Sep 17 00:00:00 2001 From: Jake Howard Date: Wed, 7 Oct 2020 17:41:28 +0100 Subject: [PATCH] Add some notes about killing long running queries etc --- notes/psql/long-running-queries.md | 38 +++++++++++++++++++++++++++ notes/psql/running-queries.md | 42 ++++++++++++++++++++++++++++++ 2 files changed, 80 insertions(+) create mode 100644 notes/psql/long-running-queries.md create mode 100644 notes/psql/running-queries.md diff --git a/notes/psql/long-running-queries.md b/notes/psql/long-running-queries.md new file mode 100644 index 0000000..20c3085 --- /dev/null +++ b/notes/psql/long-running-queries.md @@ -0,0 +1,38 @@ +--- +title: Find and kill long running queries +tags: + - PostgreSQL +link: https://medium.com/little-programming-joys/finding-and-killing-long-running-queries-on-postgres-7c4f0449e86d +--- + +# Running queries + +View a list of queries running longer than 5 minutes: + +```sql +SELECT + pid, + now() - pg_stat_activity.query_start AS duration, + query, + state +FROM pg_stat_activity +WHERE (now() - pg_stat_activity.query_start) > interval '5 minutes'; +``` + +Also see [running queries](../running-queries). + +# Stopping a given connection + +```sql +SELECT pg_cancel_backend(pid); +``` + +`pid` being the relevant value from `pg_stat_activity.pid`. + +# Killing a given connection + +```sql +SELECT pg_terminate_backend(pid); +``` + +Should be avoided, as it's synonymous with `kill -9`. diff --git a/notes/psql/running-queries.md b/notes/psql/running-queries.md new file mode 100644 index 0000000..2ab1968 --- /dev/null +++ b/notes/psql/running-queries.md @@ -0,0 +1,42 @@ +--- +title: Monitor running queries +tags: + - PostgreSQL +link: https://techmango.org/2017/11/04/monitor-running-queries-postgresql/ +--- + +View a list of running queries: + +```sql +SELECT + datname, + pid, + usename, + client_addr, + client_port, + xact_start, + backend_start, + query_start, + state, + query +FROM pg_stat_activity +ORDER BY query_start ASC +``` + +View list of non-idle connections: + +```sql +SELECT + datname, + pid, + usename, + client_addr, + client_port, + xact_start, + backend_start, + query_start +FROM pg_stat_activity +WHERE + state != 'idle' +ORDER BY query_start ASC +```