In this article, we will see how to drop a PostgreSQL database if there are active connections to it?
Below query is used to drop active connections on a database
Syntax for PostgreSQL 9.2 and later:
SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity WHERE pg_stat_activity.datname = 'TARGET_DB' -- ← change this to your DB AND pid <> pg_backend_pid();
Syntax for PostgreSQL 9.1 and below 9.1:
SELECT pg_terminate_backend(pg_stat_activity.procpid) FROM pg_stat_activity WHERE pg_stat_activity.datname = 'TARGET_DB' -- ← change this to your DB AND procpid <> pg_backend_pid();
Examples:
1. Lets try to drop database ‘lonprod2’ which contains active connections on it.
ERROR: database "lonprod2" is being accessed by other users DETAIL: There is 1 other session using the database.
2. Now run the below query to kill active connections on a specific database in PostgreSQL:
SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity WHERE pg_stat_activity.datname = 'lonprod2' AND pid <> pg_backend_pid();
Output:
pg_terminate_backend
———————-
t
3. Now try to drop database ‘lonprod2’.
postgres=# drop database lonprod2; DROP DATABASE
Same query can be used to drop all connections to a specific database in PostgreSQL.