Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to drop a PostgreSQL database if there are active connections to it?

Tags:

postgresql

I need to write a script that will drop a PostgreSQL database. There may be a lot of connections to it, but the script should ignore that.

The standard DROP DATABASE db_name query doesn't work when there are open connections.

How can I solve the problem?

like image 235
Roman Prykhodchenko Avatar asked Mar 23 '11 16:03

Roman Prykhodchenko


People also ask

How do I drop a database with connections?

Connect to SQL Server Management Studio; expand Database Node -> Right click the Databases which you want to Drop -> Select Delete from the drop-down menu to open up Delete Object dialog box as shown in the snippet below.

How do I drop a current open database?

Go to edit connections and look at the database name. Switch the connection to a different database and then drop the database you wish.

How do you disconnect a database in pgAdmin?

To disconnect from a database, click the connection in the Database Navigator or Projects view, and then click the Disconnect button in the toolbar or click Database -> Disconnect on the main menu: You can also right-click the connection and click Disconnect on the context menu.


1 Answers

This will drop existing connections except for yours:

Query pg_stat_activity and get the pid values you want to kill, then issue SELECT pg_terminate_backend(pid int) to them.

PostgreSQL 9.2 and above:

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(); 

PostgreSQL 9.1 and below:

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(); 

Once you disconnect everyone you will have to disconnect and issue the DROP DATABASE command from a connection from another database aka not the one your trying to drop.

Note the renaming of the procpid column to pid. See this mailing list thread.

like image 89
Kuberchaun Avatar answered Sep 23 '22 13:09

Kuberchaun