Skip to content

Instantly share code, notes, and snippets.

@StevenJL
Last active August 31, 2021 16:31
Show Gist options
  • Select an option

  • Save StevenJL/ad4d514e17775b0e49875fffa590ac2f to your computer and use it in GitHub Desktop.

Select an option

Save StevenJL/ad4d514e17775b0e49875fffa590ac2f to your computer and use it in GitHub Desktop.
Psql Kill Long Running Queries
/*
Kill long-running read-only queries
*/
SELECT
application_name,
pg_cancel_backend(pid), /* returns boolean indicating whether or not query was killed */
state,
age(clock_timestamp(), query_start),
usename,
query
FROM pg_stat_activity
WHERE state != 'idle'
AND query ILIKE '%SELECT%' /* Safer to kill non-state-changing queries */
AND query_start < (NOW() - INTERVAL '300 seconds'); /* older than 5 minutes */
/* You can also kill the query if you have the pid */
/* This will gracefully kill the query */
SELECT pg_cancel_backend(12345);
/* This will hard kill the query */
SELECT pg_terminate_backend(12345);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment