How to create database postgresql
How to create database postgresql
How to create database postgresql
The first test to see whether you can access the database server is to try to create a database. A running PostgreSQL server can manage many databases. Typically, a separate database is used for each project or for each user.
Possibly, your site administrator has already created a database for your use. In that case you can omit this step and skip ahead to the next section.
If this produces no response then this step was successful and you can skip over the remainder of this section.
If you see a message similar to:
then PostgreSQL was not installed properly. Either it was not installed at all or your shell’s search path was not set to include it. Try calling the command with an absolute path instead:
The path at your site might be different. Contact your site administrator or check the installation instructions to correct the situation.
Another response could be this:
This means that the server was not started, or it is not listening where createdb expects to contact it. Again, check the installation instructions or consult the administrator.
Another response could be this:
If you have a user account but it does not have the privileges required to create a database, you will see the following:
Not every user has authorization to create new databases. If PostgreSQL refuses to create databases for you then the site administrator needs to grant you permission to create databases. Consult your site administrator if this occurs. If you installed PostgreSQL yourself then you should log in for the purposes of this tutorial under the user account that you started the server as. [1]
You can also create databases with other names. PostgreSQL allows you to create any number of databases at a given site. Database names must have an alphabetic first character and are limited to 63 bytes in length. A convenient choice is to create a database with the same name as your current user name. Many tools assume that database name as the default, so it can save you some typing. To create that database, simply type:
(For this command, the database name does not default to the user account name. You always need to specify it.) This action physically removes all files associated with the database and cannot be undone, so this should only be done with a great deal of forethought.
More about createdb and dropdb can be found in createdb and dropdb respectively.
Prev | Up | Next |
1.2. Architectural Fundamentals | Home | 1.4. Accessing a Database |
Submit correction
If you see anything in the documentation that is not correct, does not match your experience with the particular feature or requires further clarification, please use this form to report a documentation issue.
Copyright © 1996-2022 The PostgreSQL Global Development Group
How to create database postgresql
CREATE DATABASE creates a new PostgreSQL database.
Parameters
The name of a database to create.
The role name of the user who will own the new database, or DEFAULT to use the default (namely, the user executing the command). To create a database owned by another role, you must be a direct or indirect member of that role, or be a superuser.
The name of the template from which to create the new database, or DEFAULT to use the default template ( template1 ).
Character set encoding to use in the new database. Specify a string constant (e.g., ‘SQL_ASCII’ ), or an integer encoding number, or DEFAULT to use the default encoding (namely, the encoding of the template database). The character sets supported by the PostgreSQL server are described in Section 24.3.1. See below for additional restrictions.
This is a shortcut for setting LC_COLLATE and LC_CTYPE at once. If you specify this, you cannot specify either of those parameters.
Collation order ( LC_COLLATE ) to use in the new database. This affects the sort order applied to strings, e.g., in queries with ORDER BY, as well as the order used in indexes on text columns. The default is to use the collation order of the template database. See below for additional restrictions.
Character classification ( LC_CTYPE ) to use in the new database. This affects the categorization of characters, e.g., lower, upper and digit. The default is to use the character classification of the template database. See below for additional restrictions.
The name of the tablespace that will be associated with the new database, or DEFAULT to use the template database’s tablespace. This tablespace will be the default tablespace used for objects created in this database. See CREATE TABLESPACE for more information.
If false then no one can connect to this database. The default is true, allowing connections (except as restricted by other mechanisms, such as GRANT / REVOKE CONNECT ).
If true, then this database can be cloned by any user with CREATEDB privileges; if false (the default), then only superusers or the owner of the database can clone it.
Optional parameters can be written in any order, not only the order illustrated above.
Notes
CREATE DATABASE cannot be executed inside a transaction block.
Errors along the line of “ could not initialize database directory ” are most likely related to insufficient permissions on the data directory, a full disk, or other file system problems.
Use DROP DATABASE to remove a database.
The program createdb is a wrapper program around this command, provided for convenience.
Database-level configuration parameters (set via ALTER DATABASE ) and database-level permissions (set via GRANT ) are not copied from the template database.
Although it is possible to copy a database other than template1 by specifying its name as the template, this is not (yet) intended as a general-purpose “ COPY DATABASE ” facility. The principal limitation is that no other sessions can be connected to the template database while it is being copied. CREATE DATABASE will fail if any other connection exists when it starts; otherwise, new connections to the template database are locked out until CREATE DATABASE completes. See Section 23.3 for more information.
The character set encoding specified for the new database must be compatible with the chosen locale settings ( LC_COLLATE and LC_CTYPE ). If the locale is C (or equivalently POSIX ), then all encodings are allowed, but for other locale settings there is only one encoding that will work properly. (On Windows, however, UTF-8 encoding can be used with any locale.) CREATE DATABASE will allow superusers to specify SQL_ASCII encoding regardless of the locale settings, but this choice is deprecated and may result in misbehavior of character-string functions if data that is not encoding-compatible with the locale is stored in the database.
The CONNECTION LIMIT option is only enforced approximately; if two new sessions start at about the same time when just one connection “ slot ” remains for the database, it is possible that both will fail. Also, the limit is not enforced against superusers or background worker processes.
Examples
To create a new database:
To create a database sales owned by user salesapp with a default tablespace of salesspace :
To create a database music with a different locale:
To create a database music2 with a different locale and a different character set encoding:
The specified locale and encoding settings must match, or an error will be reported.
Note that locale names are specific to the operating system, so that the above commands might not work in the same way everywhere.
Compatibility
There is no CREATE DATABASE statement in the SQL standard. Databases are equivalent to catalogs, whose creation is implementation-defined.
See Also
Submit correction
If you see anything in the documentation that is not correct, does not match your experience with the particular feature or requires further clarification, please use this form to report a documentation issue.
Copyright © 1996-2022 The PostgreSQL Global Development Group
How to create database postgresql
CREATE DATABASE — создать базу данных
Синтаксис
Описание
Параметры
Имя создаваемой базы данных. имя_пользователя
Классификация символов ( LC_CTYPE ), которая будет применяться в новой базе данных. Этот параметр определяет принадлежность символов категориям, например: строчные, заглавные, цифры и т. п. По умолчанию используется классификация символов, установленная в шаблоне. Дополнительные ограничения описаны ниже. табл_пространство
Если false, никто не сможет подключаться к этой базе данных. По умолчанию имеет значение true, то есть подключения принимаются (если не ограничиваются другими механизмами, например, GRANT / REVOKE CONNECT ). предел_подключений
Если true, базу данных сможет клонировать любой пользователь с правами CREATEDB ; в противном случае (по умолчанию), клонировать эту базу смогут только суперпользователи и её владелец.
Дополнительные параметры могут записываться в любом порядке, не обязательно так, как показано выше.
Замечания
CREATE DATABASE нельзя выполнять внутри блока транзакции.
Программа createdb представляет собой оболочку этой команды, созданную ради удобства.
Конфигурационные параметры уровня базы данных (устанавливаемые командой ALTER DATABASE ) и разрешения уровня базы (устанавливаемые командой GRANT ) из шаблона не копируются.
Кодировка символов, указанная для новой базы данных, должна быть совместима с выбранными параметрами локали ( LC_COLLATE и LC_CTYPE ). Если выбрана локаль C (или равнозначная ей POSIX ), допускаются все кодировки, но для других локалей правильно будет работать только одна кодировка. (В Windows, однако, кодировку UTF-8 можно использовать с любой локалью.) CREATE DATABASE позволяет суперпользователям указать кодировку SQL_ASCII вне зависимости от локали, но этот вариант считается устаревшим и может привести к ошибочному поведению строковых функций, если в базе хранятся данные в кодировке, несовместимой с заданной локалью.
Примеры
Создание базы данных:
Создание базы данных music с другой локалью:
Создание базы данных music2 с другой локалью и другой кодировкой символов:
Свойства кодировки должны соответствовать локали, иначе возникнет ошибка.
Заметьте, что имена локалей зависят от операционной системы, так что показанные выше команды могут не везде работать одинаково.
Совместимость
Оператор CREATE DATABASE отсутствует в стандарте SQL. Базы данных равнозначны каталогам, а их создание в стандарте определяется реализацией.
How to create database postgresql
CREATE DATABASE — создать базу данных
Синтаксис
Описание
Параметры
Имя создаваемой базы данных. имя_пользователя
Порядок сортировки ( LC_COLLATE ), который будет использоваться в новой базе данных. Этот параметр определяет порядок сортировки строк, например, в запросах с ORDER BY, а также порядок индексов по текстовым столбцам. По умолчанию используется порядок сортировки, установленный в шаблоне. Дополнительные ограничения описаны ниже. категория_типов_символов
Классификация символов ( LC_CTYPE ), которая будет применяться в новой базе данных. Этот параметр определяет принадлежность символов категориям, например: строчные, заглавные, цифры и т. п. По умолчанию используется классификация символов, установленная в шаблоне. Дополнительные ограничения описаны ниже. табл_пространство
Если false, никто не сможет подключаться к этой базе данных. По умолчанию имеет значение true, то есть подключения принимаются (если не ограничиваются другими механизмами, например, GRANT / REVOKE CONNECT ). предел_подключений
Если true, базу данных сможет клонировать любой пользователь с правами CREATEDB ; в противном случае (по умолчанию), клонировать эту базу смогут только суперпользователи и её владелец.
Дополнительные параметры могут записываться в любом порядке, не обязательно так, как показано выше.
Замечания
CREATE DATABASE нельзя выполнять внутри блока транзакции.
Программа createdb представляет собой оболочку этой команды, созданную ради удобства.
Конфигурационные параметры уровня базы данных (устанавливаемые командой ALTER DATABASE ) из шаблона в новую базу данных не копируются.
Кодировка символов, указанная для новой базы данных, должна быть совместима с выбранными параметрами локали ( LC_COLLATE и LC_CTYPE ). Если выбрана локаль C (или равнозначная ей POSIX ), допускаются все кодировки, но для других локалей правильно будет работать только одна кодировка. (В Windows, однако, кодировку UTF-8 можно использовать с любой локалью.) CREATE DATABASE позволяет суперпользователям указать кодировку SQL_ASCII вне зависимости от локали, но этот вариант считается устаревшим и может привести к ошибочному поведению строковых функций, если в базе хранятся данные в кодировке, несовместимой с заданной локалью.
Примеры
Создание базы данных:
Создание базы данных music с кодировкой ISO-8859-1:
Совместимость
Оператор CREATE DATABASE отсутствует в стандарте SQL. Базы данных равнозначны каталогам, а их создание в стандарте определяется реализацией.
How to create database postgresql
createdb — create a new PostgreSQL database
Synopsis
Description
createdb creates a new PostgreSQL database.
Options
createdb accepts the following command-line arguments:
Specifies the name of the database to be created. The name must be unique among all PostgreSQL databases in this cluster. The default is to create a database with the same name as the current system user.
Specifies a comment to be associated with the newly created database.
-D tablespace
—tablespace= tablespace
Specifies the default tablespace for the database. (This name is processed as a double-quoted identifier.)
Echo the commands that createdb generates and sends to the server.
-E encoding
—encoding= encoding
Specifies the character encoding scheme to be used in this database. The character sets supported by the PostgreSQL server are described in Section 24.3.1.
Specifies the LC_COLLATE setting to be used in this database.
Specifies the LC_CTYPE setting to be used in this database.
Specifies the database user who will own the new database. (This name is processed as a double-quoted identifier.)
-T template
—template= template
Specifies the template database from which to build this database. (This name is processed as a double-quoted identifier.)
Print the createdb version and exit.
Show help about createdb command line arguments, and exit.
createdb also accepts the following command-line arguments for connection parameters:
Specifies the host name of the machine on which the server is running. If the value begins with a slash, it is used as the directory for the Unix domain socket.
Specifies the TCP port or the local Unix domain socket file extension on which the server is listening for connections.
-U username
—username= username
User name to connect as.
Force createdb to prompt for a password before connecting to a database.
Specifies the name of the database to connect to when creating the new database. If not specified, the postgres database will be used; if that does not exist (or if it is the name of the new database being created), template1 will be used. This can be a connection string. If so, connection string parameters will override any conflicting command line options.
Environment
If set, the name of the database to create, unless overridden on the command line.
PGHOST
PGPORT
PGUSER
This utility, like most other PostgreSQL utilities, also uses the environment variables supported by libpq (see Section 34.15).
Diagnostics
In case of difficulty, see CREATE DATABASE and psql for discussions of potential problems and error messages. The database server must be running at the targeted host. Also, any default connection settings and environment variables used by the libpq front-end library will apply.
Examples
To create the database demo using the default database server:
See Also
Submit correction
If you see anything in the documentation that is not correct, does not match your experience with the particular feature or requires further clarification, please use this form to report a documentation issue.
Copyright © 1996-2022 The PostgreSQL Global Development Group