PostgreSQL: Drop a database which has a hyphen in name

Normally to drop a database in PostgreSQL, we can just type:

DROP DATABASE database;

Here’s a list of my current databases:

postgres=# \l
                                   List of databases
    Name     |   Owner   | Encoding |   Collate   |    Ctype    |   Access privileges   
-------------+-----------+----------+-------------+-------------+-----------------------
 dashboard   | dashboard | UTF8     | en_US.UTF-8 | en_US.UTF-8 | 
 postgres    | postgres  | UTF8     | en_US.UTF-8 | en_US.UTF-8 | 
 postgres-db | postgres  | UTF8     | en_US.UTF8  | en_US.UTF8  | 
 puppetdb    | puppetdb  | UTF8     | en_US.UTF8  | en_US.UTF8  | 
 template0   | postgres  | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +
             |           |          |             |             | postgres=CTc/postgres
 template1   | postgres  | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +
             |           |          |             |             | postgres=CTc/postgres
(6 rows)

And I want to drop a database called “postgres-db”. So, let’s try:

postgres=# DROP DATABASE postgres-db;
ERROR:  syntax error at or near "-"
LINE 1: drop database postgres-db;
                              ^

According to this, we have to escape the database name which contains a dash or hyphen in double quotation marks:

postgres=# DROP DATABASE "postgres-db";
DROP DATABASE

It works.

Leave a Reply

Your email address will not be published. Required fields are marked *