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

No, you can not. For all database engine, the answer is same, you can not drop a database if there are active connections. But PostgreSQL and some other database engines provide options to kill active connections automatically.

TL;DR: DROP DATABASE database_name WITH (FORCE);

Dropping a database with active connections

As mentioned above, it is not possible to drop database with active connections, but you can force connection meanwhile you are dropping the database:

DROP DATABASE database_name WITH (FORCE);

Killing Connections Before Dropping

There are two ways to kill connections before dropping connections. One of them is wrong way. Let’s start with it.

The Wrong Way

service postgresql stop
service postgresql start
psql
DROP DATABASE database_name;

When you restart PostgreSQL service all active connections to your server will be dropped. Since all connections will be killed immediately, your applications may throws unexpected error messages. Do not restart PostgreSQL services directly.

Correct Way: Ask PostgreSQL

SELECT pg_terminate_backend(pg_stat_activity.pid) 
FROM pg_stat_activity
WHERE pid <> get_backend_pid() --not your own connection
AND pg_stat_activity.datname == 'DBNAME';

Above query will terminate all connections to DBNAME but your own connection will remain active. After killing connections you can drop the database:

DROP DATABASE DBNAME;

You can drop an active database via following one of those methods.

Please leave a comment below! I would be happy to meet you : )

A new post everyday, subscribe now and don’t miss it!

Subscribe to our newsletter for cool news

Hi! I’m an IT Specialist

I want to hear from you! I am Working with enterprises for 10+ years to improve their infrastructure and efficiency.

Get in touch with me.

Leave a Reply

Discover more from Empower. Innovate. Transform.

Subscribe now to keep reading and get access to the full archive.

Continue reading