4

Getting the following error when trying to drop a PostgreSQL DB say "test"

postgres=# DROP DATABASE test;
ERROR:  database "test" is being accessed by other users
DETAIL:  There is 1 other session using the database.
Laurenz Albe
  • 209,280
  • 17
  • 206
  • 263
SANITH
  • 3,147
  • 3
  • 13
  • 15

2 Answers2

18

You can use pg_terminate_backend to kill open connections with a query:

PostgresVersion >=9.2

SELECT 
   pg_terminate_backend(pg_stat_activity.pid)
FROM pg_stat_activity
WHERE
   pg_stat_activity.datname = 'test'
AND pid <> pg_backend_pid()

PostgresVersion <9.2

SELECT 
   pg_terminate_backend(pg_stat_activity.procpid)
FROM 
   pg_stat_activity
WHERE 
   pg_stat_activity.datname = 'test'
AND procpid <> pg_backend_pid();

where 'test' is your databasename

For PostgreSQL Version >= 13

One can use:

DROP DATABASE mydb WITH (FORCE);

Ref: https://www.postgresql.org/docs/current/sql-dropdatabase.html

FatFreddy
  • 1,160
  • 1
  • 9
  • 16
-1

1) Run the following command and findout the pid postgres=# select * from pg_stat_activity where datname='test';

datid | datname | pid | usesysid | usename | current_query | waiting | xact_start | query_start | backend_start | client_addr | client_port -------+---------+---------+----------+----------+---------------+---------+------------+-------------------------------+-------------------------------+-------------+------------- 28091 | test | 8481 | 10 | postgres | | f | | 2008-11-12 09:12:50.277096+00 | 2008-11-12 09:11:10.328231+00 | 127.0.0.1 | 43152

2) kill -9 8481 (Here the pid is 8481)

3) Now run

postgres=# drop database test;

DROP DATABASE

SANITH
  • 3,147
  • 3
  • 13
  • 15
  • this is a really bad answer: it will very likely cause data loss or even corruption to unrelated databases on your node. You should *never* "kill -9" any DB process unless you know exactly what you are doing. As pointed out by @FatFreddy, there are postgres-specific ways of achieving this without breaking any safety guarantees. – Leo Antunes Mar 21 '19 at 15:05
  • @LeoAntunes What `pg_terminate_backend` actually [does](https://www.postgresql.org/docs/9.3/functions-admin.html) is `kill -15 8481` so this answer isn't that much wrong (it does the same, just in a more peremptory manner), but it is more explicit about what goes on under the hood. – Antony Hatchkins Sep 07 '20 at 16:19
  • @AntonyHatchkins no. There's a world of difference between `kill -15` and `kill -9`, starting with the fact that one can be caught (and even ignored) while the other cannot. My comment stands: suggesting SIGKILL in the context of DBs is reckless at best. – Leo Antunes Sep 08 '20 at 22:01
  • @LeoAntunes I absolutely agree on this particular point. SIGKILL is definitely evil when applied to an process with a db connection. – Antony Hatchkins Sep 09 '20 at 06:51