This short tutorial will show you how to completely delete a database from PostgreSQL, and provide code examples.
Before you Delete a Database…
There are a few things you should do before you try and delete a PostgreSQL database, especially if you’re working on a production server.
First, take a backup of your PostgreSQL server – just in case you delete the wrong thing, or change your mind later.
Next, make sure you’re logged in as the default postgresql admin user, or a user with permission to delete databases.
And finally, make sure you’re sure of the name of the database you want to delete, and that there’s nothing you need to keep in it, and that no other databases or systems are relying on it. Deleting cannot be undone (unless you have a backup to restore).
Deleting/Dropping/Destroying a Database in PostgreSQL with the DROP DATABASE Statement
The PostgreSQL DROP DATABASE statement is used to delete a database by name. It’s as easy to use as:
DROP DATABASE database_name;
The database, including all tables, functions, and other data in it will be deleted.
Checking that the Database Exists Before Attempting Deletion
If the database you are trying to delete doesn’t exist, you’ll get an error. This can be avoided by only deleting the database if it exists:
DROP DATABASE IF EXISTS database_name;
Almost too easy!