How to drop all connections to a specific database in postgres without stopping the server?

How to drop all connections to a specific database in postgres without stopping the server?

  • I want to drop all connections (sessions) that are currently opened to a specific postgresql database but without restarting the server or disconnecting connections to other databases. How can I so that?

  • Answer:

    Here is my answer to http://stackoverflow.com/questions/5408156/how-to-drop-a-postgresql-database-if-there-are-active-connections-to-it/19884946#19884946 on StackOverflow. Depending on your version of postgresql you might run into a bug, that makes pg_stat_activity to omit active connections from dropped users. These connections are also not shown inside pgAdminIII. If you are doing automatic testing (in which you also create users) this might be a probable scenario. In this case you need to revert to queries like: SELECT pg_terminate_backend(pg_stat_activity.procpid) FROM pg_stat_get_activity(NULL::integer) WHERE datid=(SELECT oid from pg_database where datname = 'your_database');

sorin at Database Administrators Visit the source

Was this solution helpful to you?

Other answers

The query like this should help (assuming the database is named 'db'): select pg_terminate_backend(procpid) from pg_stat_activity where datname='db'; However you have to be a superuser to disconnect other users.

Szymon Guz

This can be used to "free" a database from client connections, so that you for example can rename it: SELECT pg_terminate_backend(procpid) FROM pg_stat_activity WHERE datname='current_db'; ALTER DATABASE current_db RENAME TO old_db; ALTER DATABASE new_db RENAME TO current_db; Be aware that this might cause problematic behaviour to your client apps. Data actualy should not be currupted due to using transactions.

cysk

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.