Open In App

PostgreSQL – Rename Database

In PostgreSQL, the ALTER DATABASE RENAME TO statement is used to rename a database. The below steps need to be followed while renaming a database: 

  1. Disconnect from the database that you want to rename by connecting to a different database.
  2. Terminate all connections, connected to the database to be renamed.
  3. Now you can use the ALTER DATABASE statement to rename the database. 

Now let’s look into the below example to see how to rename a database in PostgreSQL. 



Example: 

CREATE DATABASE test_db;



test_db=# \connect postgres;

SELECT
    *
FROM
    pg_stat_activity
WHERE
    datname = 'test_db';

SELECT
    pg_terminate_backend (pid)
FROM
    pg_stat_activity
WHERE
    datname = 'test_db';

ALTER DATABASE test_db RENAME TO new_test_db; 

Article Tags :