I've faced the error even when my database is not used by anyone and I've spent some time trying to figure out the way to properly delete any database for good.
Asked
Active
Viewed 2,026 times
1
-
1[DROP DATABASE WITH (FORCE)](https://stackoverflow.com/a/59021507/5070879) may be used if v13 and above – Lukasz Szozda Apr 05 '21 at 16:52
-
Another trick: Rename the database first, to disallow new sessions to enter. Then drop the renamed database until success (after all the sessions have exited) – wildplasser Apr 05 '21 at 16:55
-
are you currently on the DB that you trying to drop? if you are with psql, run an \c to change. if you are using ppgadmin (or other gui) disconnect the db. – Frank N Stein Apr 05 '21 at 17:18
-
I actually use Azure Data Studio. And I've tried to restart the service, then immediately connect to server and then drop DB. I think, the error occurs because of PG's different approach to connections. As I understand, you can't connect to a server and with PG and always connect to certain DB. – Igor Nikiforov Apr 06 '21 at 01:06
1 Answers
3
Thanks Lukasz for suggested solution, I like it even better now. Works for PostgreSQL v13 and above.
drop database with (force)
My old answer:
select
pg_terminate_backend(pg_stat_activity.pid)
from
pg_stat_activity
where
pg_stat_activity.datname = 'DatabaseName';
drop database DatabaseName;

Igor Nikiforov
- 611
- 1
- 7
- 17