RENAME DATABASE

The RENAME DATABASE statement changes the name of a database.

Note:
It is not possible to rename a database referenced by a view. For more details, see View Dependencies.

Warning:

Database renames are not transactional. For more information, see Database renaming considerations.

Synopsis

ALTERDATABASEnameRENAMETOname

Required privileges

Only members of the admin role can rename databases. By default, the root user belongs to the admin role.

Parameters

ParameterDescription
nameThe first instance of name is the current name of the database. The second instance is the new name for the database. The new name must be unique and follow these identifier rules. You cannot rename a database if it is set as the current database or if sql_safe_updates = true.

Database renaming considerations

Database renames are not transactional. There are two phases during a rename:

  • The system.namespace table is updated. This phase is transactional, and will be rolled back if the transaction aborts.
  • The database descriptor (an internal data structure) is updated, and announced to every other node. This phase is not transactional. The rename will be announced to other nodes only if the transaction commits, but there is no guarantee on how much time this operation will take.
  • Once the new name has propagated to every node in the cluster, another internal transaction is run that declares the old name ready for reuse in another context.
    This yields a surprising and undesirable behavior: when run inside a BEGINCOMMIT block, it’s possible for a rename to be half-done - not persisted in storage, but visible to other nodes or other transactions. This violates A, C, and I in ACID). Only D is guaranteed: If the transaction commits successfully, the new name will persist after that.

This is a known limitation. For an issue tracking this limitation, see cockroach#12123.

Examples

Rename a Database

  1. > SHOW DATABASES;
  1. +---------------+
  2. | database_name |
  3. +---------------+
  4. | db1 |
  5. | db2 |
  6. | defaultdb |
  7. | postgres |
  8. | system |
  9. +---------------+
  10. (5 rows)
  1. > ALTER DATABASE db1 RENAME TO db3;
  1. > SHOW DATABASES;
  1. +---------------+
  2. | database_name |
  3. +---------------+
  4. | db2 |
  5. | db3 |
  6. | defaultdb |
  7. | postgres |
  8. | system |
  9. +---------------+
  10. (5 rows)

Rename fails (new name already in use)

  1. > ALTER DATABASE db2 RENAME TO db3;
  1. pq: the new database name "db3" already exists

See also

Was this page helpful?
YesNo