Australian cloud for business software — built and run in Sydney since 2002

NetLeverage
NetLeverage

PostgreSQL "ERROR: database "appdb" is being accessed by other users" (55006): list the sessions, then drop, rename or copy safely

Technical article
Troubleshooting

About this article: This article is reviewed against the cited sources. This is source research, not lab validation. Check the stated versions and your own requirements before making changes.

When DROP DATABASE appdb fails with ERROR: database "appdb" is being accessed by other users, at least one other session, prepared transaction or logical replication connection is attached to that database. The line after it, DETAIL: There is 1 other session using the database., says how many. List the holders first, remove them, then repeat the command. The same message stops a rename, a move of the default tablespace, and (worded "source database") a CREATE DATABASE ... TEMPLATE.

What the error means

The error has SQLSTATE 55006, named object_in_use in Appendix A. In PostgreSQL 17 source (tag REL_17_9), four commands count the other backends in the database and raise it when the count is not zero: dropping, renaming, changing the default tablespace, and creating a database from a template, where the text starts source database. The detail line has several forms: sessions only (There is %d other session using the database. and its plural), prepared transactions only, and a combined text for both. That is our reading of the code.

The manual states the rule for each command:

  • DROP DATABASE: "if anyone else is connected to the target database, this command will fail unless you use the FORCE option". It "cannot be executed while you are connected to the target database", so connect to postgres or another database first.
  • CREATE DATABASE: "no other sessions can be connected to the template database while it is being copied". It "will fail if any other connection exists when it starts".
  • ALTER DATABASE ... SET TABLESPACE: "no one can be connected to the database".
  • ALTER DATABASE ... RENAME TO: the manual says "The current database cannot be renamed". The source also refuses it while other sessions are connected.

The word other matters. Your own session on a different database does not count. A session in the target database does not either (our reading of the source), but DROP DATABASE refuses to run from inside it.

Likely causes

Cause What you see How to confirm
Application or pool connections pg_stat_activity rows for the database, from app servers Rows with the application's application_name and client_addr
A reporting, backup or admin tool left connected A few idle rows from one address client_addr and backend_start of those rows
A second psql window or GUI inside the target database A row with your own role usename and client_addr
Prepared transactions The detail line mentions prepared transactions pg_prepared_xacts has rows for the database
A logical replication slot or subscription FORCE fails or does nothing for them pg_replication_slots shows an active logical slot, or pg_subscription has the database
Clients reconnect at once after being ended The count returns each time you end the sessions New backend_start values in pg_stat_activity

Prove the cause before changing anything

Everything here only reads. Run it from postgres or any database other than the target.

1. Read the count in the DETAIL line. It is the number to match in the next step.

2. List the sessions in the target database.

SELECT pid, usename, application_name, client_addr, state, backend_type, backend_start
FROM pg_stat_activity
WHERE datname = 'appdb' AND pid <> pg_backend_pid();

The manual describes pid, usename, application_name, client_addr, state, backend_type and backend_start as columns of this view. A good result is that the rows match the count in the DETAIL line. A bad result is a count that does not match: look at steps 3 and 4.

3. List prepared transactions in that database.

SELECT gid, prepared, owner, database FROM pg_prepared_xacts WHERE database = 'appdb';

The manual says the view has "one row per prepared transaction", removed "when the transaction is committed or rolled back".

4. List logical slots and subscriptions.

SELECT slot_name, slot_type, active FROM pg_replication_slots WHERE database = 'appdb';
SELECT subname FROM pg_subscription WHERE subdbid = (SELECT oid FROM pg_database WHERE datname = 'appdb');

The manual says "Only logical slots have an associated database" and that active is "True if this slot is currently being streamed". A row with active true, or any row from the subscription query, means FORCE will not finish the job. A row in the prepared-transactions list of step 3 does the same.

5. Read the connection settings.

SELECT datname, datallowconn, datconnlimit FROM pg_database WHERE datname = 'appdb';

Fix

The cleanest route is for the application owner and the tool owner to stop their clients at the source. Those changes are made on other systems and no PostgreSQL page covers them. For clients that cannot be stopped there are three steps below, each set out in full and meant to be taken in order. If the command is a drop, one save comes before step 1. Ending sessions does not clear prepared transactions, active logical slots or subscriptions, because the manual says FORCE "doesn't terminate if prepared transactions, active logical replication slots or subscriptions are present".

Before step 1: save the database (drop only)

Step 1 stops every new connection, and pg_dump has to connect to appdb, so the dump for a drop is taken now, before step 1, and not later. Skip this save for a rename or a CREATE DATABASE ... TEMPLATE.

First save the current state:

pg_dump -Fc -f appdb-before-drop.dump appdb

This step only reads appdb and writes the one dump file. Check that the file exists and is not empty before going on. The dump is the restore source for step 3.

1. Stop new connections

First save the current state:

psql -d postgres -c "SELECT datname, datallowconn, datconnlimit FROM pg_database WHERE datname = 'appdb'" -o appdb-conn-before.txt

Disruptive step: the next statement stops every new connection to appdb. The manual says "If false then no one can connect to this database", so the application's pool fails to reconnect and users see errors until the setting is reversed.

Run:

ALTER DATABASE appdb ALLOW_CONNECTIONS false;

Only if you need to back out: the next statement changes the setting again, so connections are accepted again as soon as it runs. The saved file prints t or f, and the statement takes true or false. Use the value the file shows for datallowconn; the statement below is for a file that shows t.

ALTER DATABASE appdb ALLOW_CONNECTIONS true;

Then repeat the pg_database query. datallowconn must match the saved file.

2. End the remaining sessions

First save the current state:

psql -d postgres -c "SELECT pid, usename, application_name, client_addr, state, backend_start FROM pg_stat_activity WHERE datname = 'appdb' AND pid <> pg_backend_pid()" -o appdb-sessions-before.txt

Disruptive step: the next statement ends the sessions listed in the saved file. Each one is cut off, and its open transaction is rolled back (our reading of what terminating a session does). A statement cannot undo it, and the saved file records who was connected.

The manual says the function "Terminates the session whose backend process has the specified process ID". Use the pid values from prove step 2, one call per session, never a list pasted from another day:

SELECT pg_terminate_backend(12345);

With no timeout the function "returns true whether the process actually terminates or not", so re-run prove step 2 and check that the rows are gone. If they come back, step 1 was skipped or did not apply.

Only if you need to back out: there is none for the sessions already ended. The clients reconnect when step 1 is undone, and the saved file lists who to tell.

3. Retry the command

For a drop, the manual states "DROP DATABASE cannot be undone. Use it with care!". The statement also "cannot be executed inside a transaction block".

The save for a drop is the dump taken before step 1, appdb-before-drop.dump. It cannot be taken now, because step 1 has stopped connections to appdb.

Risk: the next statement removes the database appdb and deletes its data directory. The manual's words apply: "DROP DATABASE cannot be undone". The dump taken before step 1 is the only route back, and pg_dump of one database does not carry cluster-wide roles.

Run, connected to postgres:

DROP DATABASE appdb;

Only if you need to back out: the command below creates a new database named appdb from the saved dump. Our own reading: it fails if a database of that name exists. It brings back only what the dump held, at the time of the dump, so changes made after the dump are lost. Restore from the dump. The manual says --create makes pg_restore "Create the database before restoring into it", using the database named with -d only for the first commands.

pg_restore --create -d postgres appdb-before-drop.dump

Then list the tables in appdb and compare with what you saved. For roles and extensions, see A PostgreSQL Dump Restored with Missing Roles or Extensions: Check the Recovery Set.

After a rename or a CREATE DATABASE ... TEMPLATE that succeeded, appdb still has ALLOW_CONNECTIONS false from step 1, so open it again with the value saved in appdb-conn-before.txt; the file shows t or f, and the statement takes true or false (the statement below is for a file that shows t). If you renamed the database, use its new name in place of appdb.

Risk: the next statement accepts new connections as soon as it runs, so the application reconnects from that moment. The same statement with false stops them again.

ALTER DATABASE appdb ALLOW_CONNECTIONS true;

A rename or a CREATE DATABASE ... TEMPLATE is blocked by the same holders, so steps 1 and 2 clear the way for it too. Each of those statements is a changing step of its own, with its own save, warning and undo.

DROP DATABASE appdb WITH (FORCE) and dropdb --force do steps 2 and 3 in one go. The manual says they "Attempt to terminate all existing connections to the target database" and that "If connections would remain, this command will fail". They carry the same risk as step 3 and need the same dump from before step 1. They do not replace step 1: a pool can reconnect between the termination and the drop (our own reading).

Example (illustrative): On db01, DROP DATABASE appdb_old; fails with DETAIL: There are 3 other sessions using the database. The query in prove step 2 returns 3 rows: two from app01 with application_name orders-api, and one from 198.51.100.20 left by a reporting tool. 2 + 1 = 3, which matches. pg_prepared_xacts, pg_replication_slots and pg_subscription return no rows. The administrator saves appdb_old, sets ALLOW_CONNECTIONS false, ends the three pids, drops the database, and does not need the undo for step 1 because the database is gone.

Confirm the fix

  1. The statement completes without 55006. For a drop, SELECT datname FROM pg_database WHERE datname = 'appdb' returns no row.
  2. If the database still exists, datallowconn is true again and the application reconnects. Check that pg_stat_activity shows its sessions.
  3. The application log has no connection errors after the saved time.

What to watch afterwards

Risks and limits

  • These commands have not been run or lab-tested.
  • pg_terminate_backend can only end sessions that the calling role may end. The manual says "only superusers can terminate superuser backends".
  • A dump restores the database, not the cluster's roles, tablespaces or settings made outside it. Check the restore before relying on it.
  • Where connections run through a pooler, ending a session at the database may not end the client's connection to the pooler, which can open another at once (our own reading).
  • The message text is a reading of PostgreSQL 17 source; other releases may word it differently.

Sources

  • DROP DATABASE — PostgreSQL Global Development Group, PostgreSQL 17 documentation, no date shown, accessed 3 December 2026
  • dropdb — PostgreSQL Global Development Group, PostgreSQL 17 documentation, no date shown, accessed 3 December 2026
  • CREATE DATABASE — PostgreSQL Global Development Group, PostgreSQL 17 documentation, no date shown, accessed 3 December 2026
  • ALTER DATABASE — PostgreSQL Global Development Group, PostgreSQL 17 documentation, no date shown, accessed 3 December 2026
  • 51.15. pg_database — PostgreSQL Global Development Group, PostgreSQL 17 documentation, no date shown, accessed 3 December 2026
  • 52.16. pg_prepared_xacts — PostgreSQL Global Development Group, PostgreSQL 17 documentation, no date shown, accessed 3 December 2026
  • 52.19. pg_replication_slots — PostgreSQL Global Development Group, PostgreSQL 17 documentation, no date shown, accessed 3 December 2026
  • 51.54. pg_subscription — PostgreSQL Global Development Group, PostgreSQL 17 documentation, no date shown, accessed 3 December 2026
  • 27.2. The Cumulative Statistics System — PostgreSQL Global Development Group, PostgreSQL 17 documentation, no date shown, accessed 3 December 2026
  • 9.28. System Administration Functions — PostgreSQL Global Development Group, PostgreSQL 17 documentation, no date shown, accessed 3 December 2026
  • psql — PostgreSQL Global Development Group, PostgreSQL 17 documentation, no date shown, accessed 3 December 2026
  • pg_dump — PostgreSQL Global Development Group, PostgreSQL 17 documentation, no date shown, accessed 3 December 2026
  • pg_restore — PostgreSQL Global Development Group, PostgreSQL 17 documentation, no date shown, accessed 3 December 2026
  • Appendix A. PostgreSQL Error Codes — PostgreSQL Global Development Group, PostgreSQL 17 documentation, no date shown, accessed 3 December 2026
  • dbcommands.c — PostgreSQL source repository, tag REL_17_9, no date shown, accessed 3 December 2026