How to Drop Databases in PostgreSQL

Published: 16 May 2019
on channel: PG Casts by Hashrocket
6,619
37

This PG Casts episode is sponsored by Hashrocket, a consultancy specializing in PostgreSQL; learn more at https://hashrocket.com. To see more PG Casts videos, visit our YouTube channel or https://www.pgcasts.com

Transcript:

In this episode, we're going to look at how to drop databases in Postgres.

To begin, let's create a new database. We'll call it "example".

```sql
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.

```sql
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.

```sql
drop database example;
```

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

```sql
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.

```sql
create database example is_template true;
```

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

```sql
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.

```sql
alter database example is_template false;
```

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

```sql
drop database example;
```

Thanks for watching!


Watch video How to Drop Databases in PostgreSQL online without registration, duration hours minute second in high quality. This video was added by user PG Casts by Hashrocket 16 May 2019, don't forget to share it with your friends and acquaintances, it has been viewed on our site 6,619 once and liked it 37 people.