PostgreSQL Delete Database
PostgreSQL can delete databases using one of the following three methods:
- Use the
DROP DATABASE
SQL statement to delete.
- Use the
- Use the
dropdb
command to delete.
- Use the
- Use the
pgAdmin
tool.
- Use the
Note: Deleting a database should be done with caution, as once deleted, all information will be lost.
DROP DATABASE to Delete a Database
DROP DATABASE removes the database's catalog entry and deletes the directory containing the data.
DROP DATABASE can only be executed by a superuser or the database owner.
The DROP DATABASE command needs to be executed in the PostgreSQL command window, with the following syntax:
DROP DATABASE [ IF EXISTS ] name
Parameter Description:
IF EXISTS: Provides a notification message if the database does not exist, instead of an error message.
name: The name of the database to be deleted.
For example, to delete a database named tutorialprodb:
postgres=# DROP DATABASE tutorialprodb;
dropdb Command to Delete a Database
dropdb is a wrapper for the DROP DATABASE command.
dropdb is used to delete a PostgreSQL database.
The dropdb command can only be executed by a superuser or the database owner.
The dropdb command has the following syntax:
dropdb [connection-option...] [option...] dbname
Parameter Description:
dbname: The name of the database to be deleted.
options: Optional parameters, which can be any of the following values:
No. | Option & Description |
---|---|
1 | -e Displays the commands generated by dropdb and sends them to the database server. |
2 | -i Issues a verification prompt before performing the deletion. |
3 | -V Prints the dropdb version and exits. |
4 | --if-exists Provides a notification message if the database does not exist, instead of an error message. |
5 | --help Displays help information for the dropdb command. |
6 | -h host Specifies the host name of the server. |
7 | -p port Specifies the port the server listens on, or the socket file. |
8 | -U username The username to connect to the database. |
9 | -w Ignores password input upon connection. |
10 | -W Forces password input upon connection. |
11 | --maintenance-db=dbname Specifies the database to connect to when deleting a database, default is postgres, if it does not exist, it uses template1. |
Next, open a command window, navigate to the PostgreSQL installation directory, and go to the bin directory. The dropdb command is located in PostgreSQL installation directory/bin. Execute the command to delete the database:
$ cd /Library/PostgreSQL/11/bin/
$ dropdb -h localhost -p 5432 -U postgres tutorialprodb
password ******
The above command logs in as the superuser postgres to the PostgreSQL database at the host address localhost, port number 5432, and deletes the tutorialprodb database.
pgAdmin Tool to Delete a Database
The pgAdmin tool provides comprehensive functionality for managing databases.