PostgreSQL Rename Database
Summary: in this tutorial, you will learn step-by-step how to rename a PostgreSQL database using the ALTER DATABASE...RENAME TO
statement.
PostgreSQL rename database steps
To rename a PostgreSQL database, you use the following steps:
- First, change the current database from the one that you want to rename to a different one.
- Second, terminate all active connections to the database that you want to rename.
- Third, use the
ALTER DATABASE
statement to rename the database to the new one.
Let’s take a look at an example of renaming a database.
First, open the Command Prompt on Windows or Terminal on a Unix-like system and connect to the PostgreSQL server:
Second, create a new database called db:
We’ll rename the db
database to newdb
:
Third, if you are already connected to the PostgreSQL server, you can change the current database to a different one, for example, postgres:
Fourth, retrieve all active connections to the db
database:
The query returned the following output:
The output shows one connection to the db
database.
In practice, a database may have many active connections. In this case, you need to inform the respective users as well as the application owners before terminating connections to avoid data loss.
Fifth, terminate all the connections to the db
database:
Sixth, rename the db
database to newdb
using the ALTER DATABASE RENAME TO
statement:
Summary
- Use the
ALTER DATABASE RENAME TO
statement to rename a database from the PostgreSQL server.