Site icon JD Bots

How to Rename a Database in PostgreSQL

Card for How to Rename a Database in PostgreSQL: fix a database name with one ALTER DATABASE statement, with the steps Connect to postgres, ALTER DATABASE, RENAME TO inventory and No other sessions.

How to Rename a Database in PostgreSQL.

Made a typo in a database name, or need a better one? You can rename a database in PostgreSQL with one statement, as long as nobody is connected to it.

Every command and output on this page is real, from PostgreSQL 19 on macOS.

Syntax

Syntax

ALTER DATABASE name RENAME TO new_name;

This is one of the forms of ALTER DATABASE in the PostgreSQL documentation.

Step 1: Connect to Another Database

Connect to your server with psql as the postgres user, as Part 2 of the PostgreSQL Tutorial shows. psql connects you to the postgres database, and its prompt is postgres=#.

This guide renames a database called inventry, a typo, to inventory. To follow along, create it first:

postgres=#

CREATE DATABASE inventry;

Output

CREATE DATABASE

Step 2: Rename the Database

postgres=#

ALTER DATABASE inventry RENAME TO inventory;

Output

ALTER DATABASE

psql answers ALTER DATABASE: the database is now called inventory. Only the name changes; everything inside it stays as it was.

Clean Up

To remove the example database:

postgres=#

DROP DATABASE inventory;

Output

DROP DATABASE

Common Mistakes

MistakeWhat happensDo this instead
Renaming the database you’re connected toERROR: current database cannot be renamedConnect to another database first: \c postgres.
Renaming while someone else is connected, such as pgAdmin or another psql windowERROR: database "inventory" is being accessed by other users, with DETAIL: There is 1 other session using the database.Close the other connection first: quit the other psql window with \q, or in pgAdmin right-click the database and choose Disconnect from database.
A name that’s already takenERROR: database "postgres" already existsPick a name no other database on the server uses.

FAQ

Do I need to change anything after renaming?

Yes. Anything that connects to the database by name, such as a connection string, an app’s settings or a saved connection in pgAdmin, must use the new name.

Can I undo a rename?

Yes. Rename it back with the same statement, with the two names swapped.

Conclusion

Connect to another database, make sure nobody else is connected to the one you’re renaming, and rename it with ALTER DATABASE … RENAME TO. Only the name changes.

Additional Resources

Related

Postgres, PostgreSQL and the Slonik Logo are trademarks or registered trademarks of the PostgreSQL Community Association of Canada, and used with their permission.

Exit mobile version