Sub topic 15
Cleaning up
This chapter covers removing the practice objects you created in firstdb. It also covers what can block a drop, how to check that everything is gone, and what to leave in place. It assumes you can open psql, you know the difference between a database and a table, and you have worked through the earlier chapters that created firstdb and the books table.
Why cleanup matters
Practice objects are cheap, but they accumulate. A forgotten database uses disk space, shows up in \l listings, and can confuse you later when you create another database with a similar name. Dropping objects deliberately is also a habit worth building, because DROP is one of the least forgiving commands in SQL.
PostgreSQL does not ask for confirmation, and it has no undo. Once a DROP DATABASE or DROP TABLE commits, the data is gone unless you have a backup. For a practice database that is the goal. For any other database, check twice before you run it.
What you created
Before you remove anything, list what you made:
- A database named
firstdb. - A table named
booksinsidefirstdb, with an identity columnid. - Three rows inserted into
books. After the update and delete chapter, two remain: Dune with its year changed to 1966, and Neuromancer.
Dropping the database removes all of these at once. Dropping only the table is a smaller cleanup that leaves the database in place.
Step 1: Leave the database you want to drop
PostgreSQL refuses to drop the database you are currently connected to. If you try, you get an error like this:
ERROR: cannot drop the currently open databaseSwitch to another database first. The postgres database exists in every default installation, so it is a safe place to stand:
\c postgresThe \c meta-command closes your current connection and opens a new one. The prompt changes from firstdb=# to postgres=#. Confirm where you are if you are unsure:
SELECT current_database();Step 2: Drop the database
Now remove the practice database:
DROP DATABASE firstdb;On success, psql prints DROP DATABASE. All tables, rows, indexes, and sequences inside firstdb are removed with it. You do not need to drop books separately.
Using IF EXISTS
If you are not sure the database exists, for example when re-running a cleanup script, add IF EXISTS:
DROP DATABASE IF EXISTS firstdb;If the database is missing, PostgreSQL reports a notice instead of an error:
NOTICE: database "firstdb" does not exist, skippingThis makes the command safe to repeat. It does not make it safer to run against the wrong database, so the name still needs to be right.
Step 3: Verify the result
List the databases:
\lfirstdb should no longer appear. You should still see postgres, template0, and template1. Leave those alone. The two template databases are what PostgreSQL copies when it creates a new database, and removing them breaks CREATE DATABASE.
You can also check through SQL, which is useful in scripts:
SELECT datname
FROM pg_database
WHERE datname = 'firstdb';An empty result ((0 rows)) means the database is gone.
When the drop fails
Other sessions are connected
The most common failure is an open connection to the target database:
ERROR: database "firstdb" is being accessed by other users
DETAIL: There is 1 other session using the database.This usually happens because you left another terminal window with psql open on firstdb, or a GUI client is connected. The simplest fix is to close those sessions and run the drop again.
If you cannot find the session, list the connections to the database:
SELECT pid, usename, application_name, state
FROM pg_stat_activity
WHERE datname = 'firstdb';You can then end them from the postgres database. This disconnects those users immediately, so use it only on a database you own and no longer need:
SELECT pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE datname = 'firstdb'
AND pid <> pg_backend_pid();The pid <> pg_backend_pid() condition keeps you from terminating your own session.
PostgreSQL 13 and later also offer a shortcut that disconnects other sessions as part of the drop:
DROP DATABASE firstdb WITH (FORCE);Treat FORCE the way you treat pg_terminate_backend: it interrupts whatever those sessions were doing.
You lack permission
Only the database owner or a superuser can drop a database. If you connected as a role other than the one that created firstdb, you see:
ERROR: must be owner of database firstdbReconnect as the creating role, for example psql -h localhost -p 5432 -U postgres, and try again.
You are inside a transaction block
DROP DATABASE cannot run inside a transaction block. If you issued BEGIN earlier and never finished it, you get:
ERROR: DROP DATABASE cannot run inside a transaction blockRun ROLLBACK; or COMMIT; to end the block, then retry.
A smaller cleanup: dropping only the table
Sometimes you want to keep firstdb for further practice and remove only books. Connect to firstdb and drop the table:
\c firstdb
DROP TABLE books;If other objects depend on the table, such as a view that selects from it, PostgreSQL refuses and tells you which object depends on it. Adding CASCADE removes those dependent objects too:
DROP TABLE books CASCADE;CASCADE can delete more than you expect, so run the plain DROP TABLE first and read the error before deciding.
If you want to keep the table and remove only the rows, use TRUNCATE:
TRUNCATE TABLE books RESTART IDENTITY;RESTART IDENTITY resets the id counter, so the next inserted row gets id 1 again. Without it, numbering continues from where it left off.
The table below compares the three levels of cleanup.
| Command | Removes | Keeps | Can be undone |
|---|---|---|---|
| `DELETE FROM books;` | All rows | Table, identity counter | Yes, until you commit |
| `TRUNCATE TABLE books;` | All rows | Table definition | Yes, if run inside an open transaction |
| `DROP TABLE books;` | Table and its rows | The database | Only inside an open transaction |
| `DROP DATABASE firstdb;` | The whole database | Other databases | No |
Quitting psql
When you are finished, leave psql:
\qPressing Ctrl+D on an empty prompt does the same thing on Linux and macOS. Quitting closes your connection, which also means it can no longer block a later drop.
Things to leave in place
You do not need to uninstall PostgreSQL. The server can keep running with only its built-in databases, and you will want it for the next thing you build. A few points on what to keep or stop:
- Keep the
postgresrole and database. Many tools assume they exist. - Keep
template0andtemplate1. - If you do not want the server running in the background, stop the service using the method for your platform. On Linux with systemd that is typically
sudo systemctl stop postgresql. On macOS with Homebrew it isbrew services stop postgresql@16, adjusted to your installed version. On Windows, use the Services application and stop the PostgreSQL service. - Stopping the service does not remove data. The data directory stays on disk, and starting the service again brings the cluster back.
Fully uninstalling PostgreSQL, including its data directory, is a separate task. It deletes every database in the cluster, so only do it if you are sure none of them matter.
Cleanup checklist
- Quit or close every other
psqlsession or GUI client connected tofirstdb. - Run
\c postgresto leavefirstdb. - Run
DROP DATABASE firstdb;. - Run
\land confirmfirstdbis not listed. - Run
\qto exit psql.
Exercise
You run DROP DATABASE firstdb; while your prompt shows firstdb=#. What error do you get, and what two commands fix it?
Show answer
PostgreSQL returns ERROR: cannot drop the currently open database. Run \c postgres to connect to a different database, then run DROP DATABASE firstdb; again.
Exercise
Your drop fails with database "firstdb" is being accessed by other users. Name two ways to resolve it, and say which is the less disruptive.
Show answer
First, close the other sessions yourself (another psql window or a GUI client) and retry. This is the less disruptive option because nothing is interrupted unexpectedly. Second, end the sessions from the server by calling pg_terminate_backend(pid) for each row in pg_stat_activity for that database, or use DROP DATABASE firstdb WITH (FORCE); on PostgreSQL 13 or later. Both disconnect the other users immediately.
Exercise
You want to empty the books table but keep the table itself, and you want the next inserted row to get id 1. Which command do you use, and why is DELETE FROM books; not enough?
Show answer
Use TRUNCATE TABLE books RESTART IDENTITY;. DELETE FROM books; removes the rows but does not reset the identity counter, so the next row would continue numbering from the previous value rather than starting at 1.