Skip to content
Latchkey

dropdb: Drop a PostgreSQL Database in CI

dropdb dbname deletes a PostgreSQL database; --if-exists makes it safe to run when the database may not exist.

To reset test state between runs, dropdb removes a database in one command. The two CI concerns are tolerating a missing database and dealing with open connections that block the drop.

What it does

dropdb issues DROP DATABASE for the named database. By default it errors if the database is absent or if other sessions are connected to it. --if-exists suppresses the missing-database error and -f (Postgres 13+) forcibly terminates other connections first.

Common usage

Terminal
# safe reset: no error if it is already gone
dropdb -h db -U postgres --if-exists appdb_test
# force-drop even with open connections (Postgres 13+)
dropdb -h db -U postgres -f appdb_test

Options

FlagWhat it does
--if-existsDo not error if the database does not exist
-f / --forceTerminate other connections, then drop (v13+)
-h / -p / -UStandard connection flags
-eEcho the SQL that dropdb runs
-iPrompt before dropping (avoid in CI)

In CI

Use --if-exists in teardown so a first run (where the database was never created) does not fail the step. If a leftover test process still holds a connection, add -f on Postgres 13+ to force the drop instead of failing. Never leave the interactive -i flag on in a pipeline; it will hang waiting for confirmation.

Common errors in CI

"dropdb: error: database removal failed: ERROR: database \"appdb_test\" is being accessed by other users" means open sessions block the drop; use -f (v13+) or terminate them with pg_terminate_backend. "ERROR: database \"appdb_test\" does not exist" without --if-exists means it was already dropped; add --if-exists. "permission denied" means the role does not own the database.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →