Effortlessly Rename Your PostgreSQL Database in 3 Steps
Renaming a Database in PostgreSQL
- Basic understanding of SQL syntax.
- Access to a PostgreSQL server and a user with appropriate permissions (database owner or superuser).
Steps:
-
psql -h <host> -U <username> -d <other_database>
-
Terminate active connections: Ensure no other users are currently connected to the database you want to rename. You can use the following command to list active connections and terminate them if necessary:
SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = '<old_database_name>';
-
Rename the database: Use the
ALTER DATABASE
statement with theRENAME TO
clause to specify the new name:ALTER DATABASE <old_database_name> RENAME TO <new_database_name>;
Example:
Let's rename a database named my_old_database
to my_new_database
:
-
Connect to a different database (e.g.,
postgres
):psql -h localhost -U postgres
-
Terminate any active connections to
my_old_database
:SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = 'my_old_database';
-
Rename the database:
ALTER DATABASE my_old_database RENAME TO my_new_database;
Related Issues and Solutions:
sql postgresql