I\'m trying to drop the database I\'m currently connected to like so, but I\'m getting this error:
pq: cannot drop the currently open database
None of this worked for me since I tried to do it through pgAdmin which kept database connections open as soon as I delete them.
Solution:
C:\Program Files\PostgreSQL\11\scripts\runpsql.bat
after you supply correct information you will be able to get pg command prompt, here you can just type:
dbdrop yourdatabase
After that you might still see database in pgAdmin but now you can just simply delete it with right click and DELETE/DROP
option.
Because, you are trying to execute dropDb
command on database, to which you have open connection.
According to postgres documentation:
You cannot be connected to the database you are about to remove. Instead, connect to template1 or any other database and run this command again.
This makes sense, because when you drop the entire database, all the open connection referencing to that database becomes invalid, So the recommended approach is to connect to different database, and execute this command again.
If you are facing a situation, where a different client is connected to the database, and you really want to drop the database, you can forcibly disconnect all the client from that particular database.
For example, to forcibly disconnect all clients from database mydb
:
If PostgreSQL < 9.2
SELECT pg_terminate_backend(procpid) FROM pg_stat_activity WHERE datname = 'mydb';
Else
SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = 'mydb';
Note: This command requires superuser privileges.
Then, you can connect to different database, and run dropDb
command again.
If you encounter this problem in IntelliJ, change the schema with the following dropdown to postgres.
After that, I was able to drop a db.
I am using PostgreSQL 12 and pgAdmin-4 in Windows 10. I had to use a combination of the above answers to drop a database, which I could not drop in pgAdmin because I was unable to close all open connections in pgAdmin.
Close pgAdmin-4.
In Windows command line, assuming my server's name is postgres and my database is mydb:
C:\> psql -U postgres
I logged in with my server password.
I then closed all open connections to mydb:
postgres-# SELECT * FROM pg_stat_activity WHERE pg_stat_activity.datname='mydb';
postgres-# SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = 'mydb';
Finally, I successfully dropped mydb:
postgres-# DROP DATABASE mydb;
Now if I go back into pgAdmin-4 it is gone.