Last active
August 31, 2021 16:31
-
-
Save StevenJL/ad4d514e17775b0e49875fffa590ac2f to your computer and use it in GitHub Desktop.
Psql Kill Long Running Queries
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| 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