last_updated: 2026-05-07

Postgres DROP DATABASE WITH (FORCE)#

To terminate connections before dropping a database, you can use

DROP DATABASE foo WITH (FORCE);

This replaces the following code block for me, which I use when setting up new databases for tests that need to COMMIT [1].

REVOKE CONNECT ON DATABASE foo FROM public;

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

DROP DATABASE IF EXISTS foo;

[1]: For other tests, you should prefer transactions, e.g. TransactionTestCase.