1. PostgreSQL 9.1 and below:
SELECT pg_terminate_backend (pg_stat_activity.procpid) from pg_stat_activity WHERE = ' target_db ' and <> pg_backend_pid ();
PostgreSQL 9.2 and above:
SELECT pg_terminate_backend (pg_stat_activity.pid) from pg_stat_activity WHERE = ' target_db ' and <> pg_backend_pid ();
Once Disconnect everyone you'll have to disconnect and issue the DROP DATABASE command from a connection from anothe R Database aka Not the one your trying to drop.
Note the renaming of the procpid
column to pid
. See this mailing list thread.
of to Current session
2.
#!/usr/bin/Envbash#KillAll connections to the postgres serverif[-N" $"] ; Thenwhere="where Pg_stat_activity.datname = ' $ '" Echo "killing all connections to database ' $ '"Else Echo "killing all connections to database"fiCat<<-eof | Psql-u Postgres-d postgres SELECT pg_terminate_backend (pg_stat_activity.pid) from pg_stat_activity${where}eof
Reference:
Http://stackoverflow.com/questions/5408156/how-to-drop-a-postgresql-database-if-there-are-active-connections-to-it
Http://www.postgresql.org/docs/9.3/static/functions-info.html
How to drop a PostgreSQL database if there is active connections to it?