Ever need to drop a postgresql database, but it would not let you because there are open connections to it (from a webapp or whatever)?
Quite annoying. If on a production server, and other databases are being used, restarting postgresql is a last resort, because it generates downtime for your site (even if small).
I finally took the time to scratch around and find the answer.
As a super user, to list all of the open connections to a given database:
select * from pg_stat_activity where datname='YourDatabase';
As a superuser, to drop all of the open connections to a given database:
select pg_terminate_backend(procpid) from pg_stat_activity where datname=’YourDatabase’;
Or for 9.x, change `procpid` to `pid`
select pg_terminate_backend(pid) from pg_stat_activity where datname='YourDatabase';
—
Here are some references to the functions:
http://www.postgresql.org/docs/current/static/functions-admin.html#FUNCTIONS-ADMIN-SIGNAL-TABLE
http://www.postgresql.org/docs/8.4/static/monitoring-stats.html#MONITORING-STATS-VIEWS-TABLE