How to kill a PostgreSQL user session connection

Question: I’m executing a DROP DATABASE my_db and getting this message , how can I kill user session connections for this specific database ?

DETAIL: There is 1 other session using the database.

Answer:  This query will kill user session connections , except your connection to a specific PostgreSQL database

SELECT
pg_terminate_backend(pid)
FROM
pg_stat_activity

WHERE

-- Not my connection

pid <> pg_backend_pid()

-- only kill connections to this specific database

AND datname = 'my_database_name'
;

You may need to also execute this REVOKE CONNECT command to stop other incoming connections

REVOKE CONNECT ON DATABASE my_database FROM PUBLIC, username;

Author: Jack Vamvas

Leave a Reply

Discover more from ciquery

Subscribe now to keep reading and get access to the full archive.

Continue reading