Postgresql как изменить имя базы данных

ALTER DATABASE ALTER DATABASE — change a database Synopsis ALTER DATABASE name [ [ WITH ] option [ ... ] …

ALTER DATABASE — change a database

Synopsis

ALTER DATABASE name [ [ WITH ] option [ ... ] ]

where option can be:

    ALLOW_CONNECTIONS allowconn
    CONNECTION LIMIT connlimit
    IS_TEMPLATE istemplate

ALTER DATABASE name RENAME TO new_name

ALTER DATABASE name OWNER TO { new_owner | CURRENT_ROLE | CURRENT_USER | SESSION_USER }

ALTER DATABASE name SET TABLESPACE new_tablespace

ALTER DATABASE name REFRESH COLLATION VERSION

ALTER DATABASE name SET configuration_parameter { TO | = } { value | DEFAULT }
ALTER DATABASE name SET configuration_parameter FROM CURRENT
ALTER DATABASE name RESET configuration_parameter
ALTER DATABASE name RESET ALL

Description

ALTER DATABASE changes the attributes of a database.

The first form changes certain per-database settings. (See below for details.) Only the database owner or a superuser can change these settings.

The second form changes the name of the database. Only the database owner or a superuser can rename a database; non-superuser owners must also have the CREATEDB privilege. The current database cannot be renamed. (Connect to a different database if you need to do that.)

The third form changes the owner of the database. To alter the owner, you must own the database and also be a direct or indirect member of the new owning role, and you must have the CREATEDB privilege. (Note that superusers have all these privileges automatically.)

The fourth form changes the default tablespace of the database. Only the database owner or a superuser can do this; you must also have create privilege for the new tablespace. This command physically moves any tables or indexes in the database’s old default tablespace to the new tablespace. The new default tablespace must be empty for this database, and no one can be connected to the database. Tables and indexes in non-default tablespaces are unaffected.

The remaining forms change the session default for a run-time configuration variable for a PostgreSQL database. Whenever a new session is subsequently started in that database, the specified value becomes the session default value. The database-specific default overrides whatever setting is present in postgresql.conf or has been received from the postgres command line. Only the database owner or a superuser can change the session defaults for a database. Certain variables cannot be set this way, or can only be set by a superuser.

Parameters

name

The name of the database whose attributes are to be altered.

allowconn

If false then no one can connect to this database.

connlimit

How many concurrent connections can be made to this database. -1 means no limit.

istemplate

If true, then this database can be cloned by any user with CREATEDB privileges; if false, then only superusers or the owner of the database can clone it.

new_name

The new name of the database.

new_owner

The new owner of the database.

new_tablespace

The new default tablespace of the database.

This form of the command cannot be executed inside a transaction block.

REFRESH COLLATION VERSION

Update the database collation version. See Notes for background.

configuration_parameter
value

Set this database’s session default for the specified configuration parameter to the given value. If value is DEFAULT or, equivalently, RESET is used, the database-specific setting is removed, so the system-wide default setting will be inherited in new sessions. Use RESET ALL to clear all database-specific settings. SET FROM CURRENT saves the session’s current value of the parameter as the database-specific value.

See SET and Chapter 20 for more information about allowed parameter names and values.

Notes

It is also possible to tie a session default to a specific role rather than to a database; see ALTER ROLE. Role-specific settings override database-specific ones if there is a conflict.

Examples

To disable index scans by default in the database test:

ALTER DATABASE test SET enable_indexscan TO off;

Compatibility

The ALTER DATABASE statement is a PostgreSQL extension.

PostgreSQL Rename Database

Introduction to PostgreSQL Rename Database

PostgreSQL renamed the database statement used to change the database name to another name; we can rename any database using the alter database statement. To rename the database in PostgreSQL, we first need to disconnect from the database from which we have connected; after disconnecting from the database, we need to connect to a different database. To rename any database in PostgreSQL, we must need the privileges of the owner of the database or need to admin of the database server. If we have to change the database name after database creation, we have changed or renamed the database name using the alter database statement.

Syntax

Below is the syntax of the renamed database in PostgreSQL.

Alter database old_database_name (Name of database which was we have change to different name.) RENAME TO new_database_name (New name of database which was we have changing.)

Below is the parameter description syntax of the renamed database

  • Alter database –We have using the alter database statement to rename the database with a different name. We can also use the alter database statement to change the feature of the database.
  • Old database name –This is defined as an old database name from the database server, which we have renamed to a different name.
  • Rename To –This keyword is defined as using this keyword we can change the database name with a different name in PostgreSQL. We have used rename to keyword with alter database statement in PostgreSQL.
  • New database name –This is defined as the new database name, which we have changed using the alter database command. This parameter is also important with the alter the database statement to change the database name.

How to Rename Database in PostgreSQL using various methods?

  • Below are the various methods which were used in PostgreSQL to rename the database in PostgreSQL.
  • We have renamed the database by using the alter database statement in PostgreSQL are as follows.
  • To rename the database using an alter database statement, we need to have superuser privileges or owner of the database privileges to rename the database.
  • The below example shows that we need to have superuser privileges or admin privileges to change the database name in PostgreSQL.

psql -U postgres -d postgres
alter database db_testing rename to db_test;
psql -U db_test -d postgres
alter database db_test rename to db_testing;

PostgreSQL Rename Database output 1

  • In the above first example, we have to change the name from Postgres user, Postgres user has privileges of a superuser; using superuser privileges, it is possible to change the name of the database.
  • In the second example, we have to change the name from db_test user; db_test user doesn’t have privileges to rename the database.
  • If we have to change the database name, we need to disconnect from the current database and connect to another database.
  • The below example shows that we need to change the database connection before renaming the database with a different name.

psql -U postgres -d postgres
c db_test
alter database db_test rename to db_testing;
c postgres
alter database db_test rename to db_testing;

PostgreSQL Rename Database output 2

  • In the above example, we have renamed the database by disconnecting the database with a different database.

To change the database name, we need to follow the below steps.

  • First, we need super user privileges or admin privileges to change the database name in PostgreSQL.
  • Disconnect from the database which name we have changing with a different name.
  • Disconnect all the session which was connected to the database, to check this session by using the pg_stat_activity catalog table.
  • Check all active sessions and terminate the same using the pg_terminate_backend command in PostgreSQL.

1. Rename database by using alter database statement –

  • Below is the example of rename a database using an alter database statement in PostgreSQL.
  • In the below example, we have to change the database name by using alter database statement in PostgreSQL.
  • In the below example, we have to change the database name from db_testing to db_test.
  • We have used Postgres user to change the database name in PostgreSQL.

l+
alter database db_testing rename to db_test;
l+

PostgreSQL Rename Database output 3

2. Alter the database using a command prompt

  • In the below example, we have to change the database name from the command prompt by using the alter database statement in PostgreSQL.
  • We have to change the database name by using Postgres user, Postgres user is the admin user of the database server.
  • In the above example, we have to change the database name from db_test to db_test_new by using the alter database statement.

output 4

3. Alter the database to change the name by disconnecting the sessions

  • In the below example, we have to change the database name by disconnecting the session from the database.
  • We have to change the database name from db_test_new to db_test are as follows.
  • We have to change the database name by using Postgres user after disconnecting all the session which was connected to db_test_new database.

select * from pg_stat_activity where datname='db_test_new';
alter database db_test_new rename to db_test;
l+

output 5

  • In the above example, we have checked the active sessions by using the pg_stat_activity catalog table.
  • Using this catalog table, we have checked the connected session of the db_test_new database. It will show the zero session is connected to the db_test_new database.
  • After successfully disconnecting all the sessions, we have renamed the database name as db_test_new to db_test in PostgreSQL.

Conclusion

We have renamed the database by using the alter database statement in PostgreSQL. We can rename the database using shell prompt as well as from database prompt. To rename the database in PostgreSQL, we need to have the privileges of the owner of the database or need to have super user privileges.

Recommended Articles

This is a guide to PostgreSQL Rename Database. Here we discuss How to Rename a Database in PostgreSQL using various methods. How to Rename Database in PostgreSQL using various methods

  1. PostgreSQL Wal
  2. Postgresql Count
  3. PostgreSQL Lock Table
  4. PostgreSQL Clustered Index

Description

ALTER DATABASE изменяет атрибуты базы данных.

Первая форма изменяет некоторые настройки для каждой базы данных.(Подробнее см.ниже.)Только владелец базы данных или суперпользователь может изменить эти настройки.

Вторая форма меняет имя базы данных. Только владелец базы данных или суперпользователь может переименовать базу данных; Владельцы, не являющиеся суперпользователями, также должны иметь привилегию CREATEDB . Текущая база данных не может быть переименована. (Подключитесь к другой базе данных, если вам нужно это сделать.)

Третья форма меняет владельца базы данных. Чтобы изменить владельца, вы должны владеть базой данных, а также быть прямым или косвенным членом новой роли-владельца и иметь привилегию CREATEDB . (Обратите внимание, что суперпользователи получают все эти привилегии автоматически.)

Четвертая форма изменяет табличное пространство БД по умолчанию.Это может сделать только владелец БД или суперпользователь;необходимо также создать привилегии для нового табличного пространства.Эта команда физически перемещает любые таблицы или индексы в старом табличном пространстве БД по умолчанию в новое табличное пространство.Новое табличное пространство по умолчанию должно быть пустым для этой БД,и никто не может быть подключен к БД.Таблицы и индексы в табличном пространстве не по умолчанию не затрагиваются.

Остальные формы изменяют значение сеанса по умолчанию для переменной конфигурации времени выполнения для базы данных PostgreSQL. Каждый раз, когда впоследствии в этой базе данных запускается новый сеанс, указанное значение становится значением сеанса по умолчанию. Значение по умолчанию для конкретной базы данных переопределяет любой параметр, присутствующий в postgresql.conf или полученный из командной строки postgres . Только владелец базы данных или суперпользователь может изменять параметры сеанса по умолчанию для базы данных. Некоторые переменные не могут быть установлены таким образом или могут быть установлены только суперпользователем.

Notes

Также возможно привязать сеанс по умолчанию к конкретной роли, а не к базе данных; см. ALTER ROLE . Параметры, относящиеся к роли, переопределяют параметры, относящиеся к базе данных, в случае конфликта.

Понравилась статья? Поделить с друзьями:
  • Postgresql как изменить владельца таблицы
  • Postgresql there has been an error
  • Postgresql syntax error at or near where
  • Postgresql syntax error at or near select
  • Postgresql syntax error at or near insert