Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Kill all Running Connections and Sessions of a Database

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:

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:

SELECT pg_terminate_backend(pg_stat_activity.pid)
FROM pg_stat_activity
WHERE datname = current_database()
  AND pid <> pg_backend_pid();

Comments

Popular posts from this blog

How to find the server is whether standby (slave) or primary(master) in Postgresql replication ?

7 Steps to configure BDR replication in postgresql

How to Get Table Size, Database Size, Indexes Size, schema Size, Tablespace Size, column Size in PostgreSQL Database

Ora2PG - Oracle/MySQL to Postgres DB migration Version 20.0

PostgreSQL Introduction