This article is half-done without your Comment! *** Please share your thoughts via Comment ***
In this post, I am sharing a script to kill all running connections and sessions of a PostgreSQL Database.
I need this script during the PostgreSQL maintenance task, in which we require to close all connections and sessions.
Before executing this script, please take care and verify all running connections and processes otherwise this script will harm to your data or transactions.
You may require this type of script very occasionally, but I am sharing because this is also one of the necessary scripts for PostgreSQL DBA.
This script will work after PostgreSQL 9.1.
Script to kill all running connections by specifying a database name:
1 2 3 4 |
SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity WHERE datname = 'datbase_name' AND pid <> pg_backend_pid(); |
Script to kill all running connections of a current database:
1 2 3 4 |
SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity WHERE datname = current_database() AND pid <> pg_backend_pid(); |