PG Casts

Dropping Databases

Episode #27 hosted by Mary Lee

Hey everyone, today we're going to look at how to drop databases in Postgres.

Postgres Version 11

Transcript

To begin, let’s create a new database. We’ll call it “example”.

create database example;

We can drop databases in Postgres using the “drop database” command. This command requires the name of the database we wish to drop.

drop database example;

The drop database command has an “if exists” flag, to prevent any errors that may be raised if we try to remove a database that doesn’t exist.

We can see such an error if we try to remove our example database again.

drop database example;

However, if we add the “if exists” flag, we no longer receive the error.

drop database if exists example;

One final note on dropping databases is that it is not possible to drop a template database.

To explore this behavior, let’s first create a template database.

create database example is_template true;

When we try to drop the database, we can see that Postgres throws an error.

drop database example;

To drop a template database, we must first update it to no longer be a template. We can do this with the “alter database” command, setting is template to false.

alter database example is_template false;

We can now run our drop database command again to see that it runs successfully.

drop database example;

Thanks for watching!

Stay up-to-date with PG Casts news!