Sub topic 15
Cleaning Up Your PostgreSQL Practice Objects
Assume you have completed the earlier exercises and created a database named firstdb containing a table named books. You should also know how to start psql, switch databases, and run SQL statements.
Cleanup means removing objects you no longer need. PostgreSQL treats database removal as a destructive operation. DROP DATABASE removes the database and everything inside it, including tables, rows, indexes, and other objects. This action cannot be undone unless you have a backup.
Choose the right cleanup action
Use the smallest action that matches your goal.
| Goal | Command | Effect |
|---|---|---|
| Remove rows but keep the table | `DELETE FROM books;` | Keeps the table definition |
| Remove one table | `DROP TABLE books;` | Removes the table and its data |
| Remove the practice database | `DROP DATABASE firstdb;` | Removes the database and all its objects |
A DELETE statement changes data inside a table. A DROP statement removes the object itself. Do not use DROP DATABASE when you only want to empty a table.
Drop a table but keep the database
If you want to keep firstdb for more practice but remove the books table, connect to firstdb and drop the table:
\c firstdb
DROP TABLE books;The \c command is a psql meta-command. It changes the database used by the current session. DROP TABLE books; removes the table and its rows.
If another object depends on the table, PostgreSQL may refuse to drop it. That refusal protects dependent objects. You can inspect the dependencies before deciding whether more removal is appropriate. Avoid adding CASCADE casually. DROP TABLE books CASCADE; can also remove objects that depend on books.
Drop the practice database
PostgreSQL does not allow you to drop the database to which your current session is connected. First switch to another database, such as the default postgres database:
\c postgres
DROP DATABASE firstdb;The first command changes the active connection. The second removes firstdb and all objects inside it.
You can verify that the database is gone by listing databases:
\lIf firstdb does not appear, the cleanup succeeded. The \l command lists databases; it does not query a table.
Common cleanup errors
database "firstdb" is being accessed by other users: another session is connected. Close those sessions before trying again. On supported PostgreSQL versions, an administrator may useDROP DATABASE firstdb WITH (FORCE);, but this disconnects other users.cannot drop the currently open database: run\c postgresfirst.database "firstdb" does not exist: check the spelling with\l.permission denied: your role does not own the database or have sufficient privileges. Ask an administrator or use the role that created it.
Exercise
Why must you connect to postgres before dropping firstdb?
Show answer
PostgreSQL does not allow a session to drop the database it is currently using, so you must connect to a different database first.