[Fixed] ERROR: database is being accessed by other users in PostgreSQL: Step-by-Step Troubleshooting Guide

Quick Summary: The error ERROR: database "<db_name>" is being accessed by other users (DETAIL: There are N other sessions using the database) occurs in PostgreSQL when you attempt to run DROP DATABASE, ALTER DATABASE ... RENAME, or restore a clean test database while idle web server pools, GUI clients (pgAdmin, DBeaver, DataGrip), or background workers still hold open connections to that database.

Understanding the Root Causes

PostgreSQL enforces strict exclusivity during destructive database-level operations like dropping, renaming, or using a database as a template. Even if a client is completely idle and not executing queries, an open TCP or Unix socket session prevents the operation. Common culprits include:

  • Database GUI Clients: Open query tabs or background metadata explorers in pgAdmin, DBeaver, TablePlus, or VS Code extensions holding persistent connections.
  • Application Connection Pools: Local dev servers (Django, Rails, Node.js/Prisma, Spring Boot) or Docker containers keeping minimum idle connections open.
  • Self-Connection Mistake: Attempting to run DROP DATABASE mydb; while your psql session is currently connected to mydb instead of the administrative postgres database.

Step 1: Quick Fix – Use DROP DATABASE WITH (FORCE) (PostgreSQL 13+)

If you are running PostgreSQL 13 or newer, you do not need to manually query and kill PIDs. First connect to a different database (such as postgres) and use the built-in FORCE option:

# 1. Connect to the 'postgres' maintenance database (NOT the target database)
psql -U postgres -d postgres

# 2. Drop the database and automatically terminate all active connections (PG 13+)
DROP DATABASE mydb WITH (FORCE);

# Or from the OS terminal using the dropdb CLI wrapper (PG 13+):
dropdb -U postgres --force mydb

Step 2: Manually Terminate Active Sessions (PostgreSQL 12 and Older)

On older PostgreSQL versions—or when you want to rename a database or inspect who is connected before disconnecting them—disallow new connections briefly and terminate existing backend PIDs via pg_stat_activity:

-- 1. Connect to the 'postgres' database
psql -U postgres -d postgres

-- 2. Inspect which users/applications are holding connections open
SELECT pid, usename, application_name, client_addr, state
FROM pg_stat_activity
WHERE datname = 'mydb';

-- 3. Prevent new connections from sneaking back in during cleanup (optional)
REVOKE CONNECT ON DATABASE mydb FROM PUBLIC;

-- 4. Terminate all other connections to 'mydb'
SELECT pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE datname = 'mydb'
  AND pid <> pg_backend_pid();

-- 5. Now drop (or rename) the database cleanly
DROP DATABASE mydb;

Step 3: Prevent Reconnection Races in Docker & CI Pipelines

In local Docker Compose setups or automated test scripts, backend containers with connection pools often reconnect within milliseconds after pg_terminate_backend() runs. Stop the app container or lock connection permissions before dropping:

# Option A: Temporarily stop the application container before resetting the DB
docker compose stop web worker
docker compose exec db psql -U postgres -c "DROP DATABASE mydb WITH (FORCE);"
docker compose exec db psql -U postgres -c "CREATE DATABASE mydb;"
docker compose start web worker

# Option B: Use alter database to disable connections temporarily (if renaming/restoring)
ALTER DATABASE mydb WITH ALLOW_CONNECTIONS = false;
SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = 'mydb' AND pid <> pg_backend_pid();
ALTER DATABASE mydb RENAME TO mydb_archive;
ALTER DATABASE mydb_archive WITH ALLOW_CONNECTIONS = true;

Verification & Testing Steps

Confirm that zero active sessions remain on the target database and that the drop or rename succeeded:

# 1. Verify no sessions remain connected to the target database
psql -U postgres -c "SELECT count(*) FROM pg_stat_activity WHERE datname = 'mydb';"
# Expected output: 0

# 2. List all databases to confirm the database was removed or recreated cleanly
psql -U postgres -c "\l"

Troubleshooting Summary Comparison

PostgreSQL Version / Scenario Primary Root Cause Recommended Solution
PostgreSQL 13+ (Local / Docker) Idle GUI or app connections Run DROP DATABASE mydb WITH (FORCE);
PostgreSQL 12 or older WITH (FORCE) syntax unsupported Run pg_terminate_backend(pid) on pg_stat_activity first
Renaming DB / Restoring Template WITH (FORCE) only applies to DROP Set ALLOW_CONNECTIONS = false, terminate PIDs, then rename
App pool reconnects immediately Containerized app auto-retrying TCP connections Stop app service via docker compose stop or revoke connect first

Leave a Reply