How to create postgresql database windows

1.3. Creating a Database The first test to see whether you can access the database server is to try to create …

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.

To create a new database, in this example named mydb, you use the following command:

$ createdb mydb

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:

createdb: command not found

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:

$ /usr/local/pgsql/bin/createdb mydb

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:

createdb: error: connection to server on socket "/tmp/.s.PGSQL.5432" failed: No such file or directory
        Is the server running locally and accepting connections on that socket?

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:

createdb: error: connection to server on socket "/tmp/.s.PGSQL.5432" failed: FATAL:  role "joe" does not exist

where your own login name is mentioned. This will happen if the administrator has not created a PostgreSQL user account for you. (PostgreSQL user accounts are distinct from operating system user accounts.) If you are the administrator, see Chapter 22 for help creating accounts. You will need to become the operating system user under which PostgreSQL was installed (usually postgres) to create the first user account. It could also be that you were assigned a PostgreSQL user name that is different from your operating system user name; in that case you need to use the -U switch or set the PGUSER environment variable to specify your PostgreSQL user name.

If you have a user account but it does not have the privileges required to create a database, you will see the following:

createdb: error: database creation failed: ERROR:  permission denied to create database

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:

$ createdb

If you do not want to use your database anymore you can remove it. For example, if you are the owner (creator) of the database mydb, you can destroy it using the following command:

$ dropdb mydb

(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.

CREATE DATABASE — create a new database

Synopsis

CREATE DATABASE name
    [ WITH ] [ OWNER [=] user_name ]
           [ TEMPLATE [=] template ]
           [ ENCODING [=] encoding ]
           [ STRATEGY [=] strategy ] ]
           [ LOCALE [=] locale ]
           [ LC_COLLATE [=] lc_collate ]
           [ LC_CTYPE [=] lc_ctype ]
           [ ICU_LOCALE [=] icu_locale ]
           [ LOCALE_PROVIDER [=] locale_provider ]
           [ COLLATION_VERSION = collation_version ]
           [ TABLESPACE [=] tablespace_name ]
           [ ALLOW_CONNECTIONS [=] allowconn ]
           [ CONNECTION LIMIT [=] connlimit ]
           [ IS_TEMPLATE [=] istemplate ]
           [ OID [=] oid ]

Description

CREATE DATABASE creates a new PostgreSQL database.

To create a database, you must be a superuser or have the special CREATEDB privilege. See CREATE ROLE.

By default, the new database will be created by cloning the standard system database template1. A different template can be specified by writing TEMPLATE name. In particular, by writing TEMPLATE template0, you can create a pristine database (one where no user-defined objects exist and where the system objects have not been altered) containing only the standard objects predefined by your version of PostgreSQL. This is useful if you wish to avoid copying any installation-local objects that might have been added to template1.

Parameters

name

The name of a database to create.

user_name

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.

template

The name of the template from which to create the new database, or DEFAULT to use the default template (template1).

encoding

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.

strategy

Strategy to be used in creating the new database. If the WAL_LOG strategy is used, the database will be copied block by block and each block will be separately written to the write-ahead log. This is the most efficient strategy in cases where the template database is small, and therefore it is the default. The older FILE_COPY strategy is also available. This strategy writes a small record to the write-ahead log for each tablespace used by the target database. Each such record represents copying an entire directory to a new location at the filesystem level. While this does reduce the write-ahead log volume substantially, especially if the template database is large, it also forces the system to perform a checkpoint both before and after the creation of the new database. In some situations, this may have a noticeable negative impact on overall system performance.

locale

This is a shortcut for setting LC_COLLATE and LC_CTYPE at once.

Tip

The other locale settings lc_messages, lc_monetary, lc_numeric, and lc_time are not fixed per database and are not set by this command. If you want to make them the default for a specific database, you can use ALTER DATABASE ... SET.

lc_collate

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.

lc_ctype

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.

icu_locale

Specifies the ICU locale ID if the ICU locale provider is used.

locale_provider

Specifies the provider to use for the default collation in this database. Possible values are: icu, libc. libc is the default. The available choices depend on the operating system and build options.

collation_version

Specifies the collation version string to store with the database. Normally, this should be omitted, which will cause the version to be computed from the actual version of the database collation as provided by the operating system. This option is intended to be used by pg_upgrade for copying the version from an existing installation.

See also ALTER DATABASE for how to handle database collation version mismatches.

tablespace_name

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.

allowconn

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).

connlimit

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

istemplate

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.

oid

The object identifier to be used for the new database. If this parameter is not specified, PostgreSQL will choose a suitable OID automatically. This parameter is primarily intended for internal use by pg_upgrade, and only pg_upgrade can specify a value less than 16384.

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 encoding and locale settings must match those of the template database, except when template0 is used as template. This is because other databases might contain data that does not match the specified encoding, or might contain indexes whose sort ordering is affected by LC_COLLATE and LC_CTYPE. Copying such data would result in a database that is corrupt according to the new settings. template0, however, is known to not contain any data or indexes that would be affected.

There is currently no option to use a database locale with nondeterministic comparisons (see CREATE COLLATION for an explanation). If this is needed, then per-column collations would need to be used.

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:

CREATE DATABASE lusiadas;

To create a database sales owned by user salesapp with a default tablespace of salesspace:

CREATE DATABASE sales OWNER salesapp TABLESPACE salesspace;

To create a database music with a different locale:

CREATE DATABASE music
    LOCALE 'sv_SE.utf8'
    TEMPLATE template0;

In this example, the TEMPLATE template0 clause is required if the specified locale is different from the one in template1. (If it is not, then specifying the locale explicitly is redundant.)

To create a database music2 with a different locale and a different character set encoding:

CREATE DATABASE music2
    LOCALE 'sv_SE.iso885915'
    ENCODING LATIN9
    TEMPLATE template0;

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.

In this PostgreSQL tutorial, we will discuss that, How to create a database in Postgresql in different ways and will cover the below topic:

  • How to create database in postgresql
  • How to create database in postgresql in linux
  • How to create database in postgresql in windows
  • How to create database in postgresql in mac
  • How to create database in postgresql using psql
  • How to create database in postgresql using CREATE DATABASE
  • How to create database in postgresql using createdb
  • How to create database in postgresql using pgadmin 4
  • Postgresql create database
  • Postgresql create database command line
  • Postgresql create database and user
  • Postgresql create database if not exists
  • Postgresql create database command line ubuntu
  • Postgresql create database with owner
  • Postgresql create database not working
  • Postgresql create database link
  • Postgresql create database and table
  • Postgresql create database and schema
  • Postgresql create database and set owner
  • Postgresql create database and role

There are mainly two ways to create a database in Postgresql:

  • By using psql, which is a terminal-based interaction to PostgreSQL, that provide you a way to type queries, and interactively show you the query results.
  • And by using pgadmin, which is a web-based, Open Source management tool for Postgres. And pgAdmin 4 provides a graphical interface that simplify the creation, maintenance and use of database objects.

How to create database in postgresql using psql

Below shown are the ways to create a database in Postgresql using psql in 3 major Operating Systems:

How to create database in postgresql in linux

First, locate the location of the psql on the operating system:

Open the terminal and try the following command:

[root@localhost data]# which psql

It will give you the path. And you don’t need to browse for it as the path is already known by the OS.

However, if it shows errors, you can locate the psql by using the find command to search the file by writing the following command on the terminal:   

[root@localhost /]# find / -name psql

Now, you have to browse the path to open the psql utility. Copy the path say, /usr/edb/as11/bin/psql

[root@localhost /]# cd /usr/edb/as11/bin

Connecting psql  

Now since you have located psql. Let’s understand the basic parameters required to connect to the database and launch psql:

Server [localhost] -h: It specifies the address for the server. You can use an IP address or the hostname of the machine on which the database server is running. By default it is localhost

Database [postgres] -d: It specifies the name of the database with which you want to connect. By default, it will be the name of the user.

Port [5432] -p: It specifies the port on which you have configured your instance while installing or initializing. By default, the port is 5432.

Username [postgres] -U: It specifies the username created while installing the PostgreSQL’s psql takes place. By default the username is Postgres.

The command shown below will start the psql in localhost initializing the Postgres database with the default parameters:

[root@localhost /]# bash-4.2$ psql -d postgres -U postgres 

If a connection has to be made to a remote server the syntax for that command will be as shown below:

[root@localhost /]# bash-4.2$ psql -h <hostname or ip address> -p <port number of remote machine> -d <database name to connect> -U <username of the remote database server>

Read PostgreSQL ADD COLUMN + 17 Examples

How to create database in postgresql in windows

First, locate the location of the psql on the operating system:

On Windows, psql will be in the Program Files, and you should be able to launch it in a command prompt simply by clicking it.

locating psql in windows
Location of the psql in Windows

Read PostgreSQL vs SQL Server

How to create database in postgresql in mac

On a Mac psql can be locate under the Applications > PostgreSQL (version number) > SQL Shell (psql). And you should be able to launch it in a terminal simply by clicking it.

You can use either of the two commands given below to create a database in Postgresql using psql after opening the psql utility on any of the 3 major operating systems discussed above:

  1. CREATE DATABASE
  2. createdb

How to create database in postgresql using CREATE DATABASE, a SQL command/query

Syntax:

postgres-# CREATE DATABASE database_name
    [ [ WITH ] [ OWNER [=] user_name ]
           [ TEMPLATE [=] template ]
           [ ENCODING [=] encoding ]
           [ LOCALE [=] locale ]
           [ LC_COLLATE [=] lc_collate ]
           [ LC_CTYPE [=] lc_ctype ]
           [ TABLESPACE [=] tablespace_name ]
           [ ALLOW_CONNECTIONS [=] allowconn ]
           [ CONNECTION LIMIT [=] connlimit ]
           [ IS_TEMPLATE [=] istemplate ] ];

The “CREATE DATABASE" command will create a new PostgreSQL database with the name database_name.

Parameters:

  • database_name: You can specify the name of a database to be create.
  • user_name: You can specify the role name of the user who will own the new database, or just write DEFAULT (it will set the owner to be the user executing the command). If you want to create a database owned by another role, then you must be a direct or indirect member of that role or be a superuser.
  • template: You can specify the name of the template which will be cloned and from which the new database will be created, or write DEFAULT to use the default template (the standard system database template1).
  • encoding: You can specify the character set encoding to use in the new database by specifying a string constant (like 'SQL_ASCII'), or an integer encoding number, or write DEFAULT to use the default encoding (that will set the encoding of the template database). You can specify any character set’s encoding supported by PostgreSQL server.
  • locale: It is used to set LC_COLLATE and LC_CTYPE parameters at once. If you specify it, you cannot specify either of the two parameters.
  • lc_collate: You can specify the collation order (LC_COLLATE) to use in the database created. This will affect 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 collation order used is of the template database.
  • lc_ctype: You can specify the character classification (LC_CTYPE) to use in the database created. This will affect the categorization of characters, e.g., lower case, upper case and digit. The default character classification used is of the template database.
  • tablespace_name: You can specify the name of the tablespace that will be associated with the database created, or write DEFAULT for using the tablespace of template database. All the objects that will be created in this database will have this tablespace by default.
  • allowconn: The default value for this is true allowing connections (except restricted ones). but if set as false then no one can connect to this database.
  • connlimit: You can specify the number of concurrent connections that can be made to the database created. By default the value is -1, that means no limit.
  • istemplate: This parameter can specify the CREATEDB privileges. that is if set as true, then this database can be cloned by any user, but if set as false (the default value), then only the owner of the database or the superusers can clone it.

Note:

  • To create any database, you must be a superuser/or have the special CREATEDB privilege in postgresql.
  • CREATE DATABASE cannot be executed inside a transaction block.
  • There is no restriction in the order of the parameters as described in the syntax above.

Examples:

postgres-# l
show list of databases in postgresql
List the databases in Postgresql
postgres=# CREATE DATABASE testdb;
create database in postgres
CREATE DATABASE command/query

Next, to confirm the database creation, you can use the following command given below

postgres=# l

Verifying the newly created database in postgresql

Verifying the newly created database

How to create database in postgresql using createdb, a command-line executable

Syntax:

postgres-# createdb [option...] [dbname [description]]

Parameters:

  • dbname: Specifies the name of a database to create.
  • description: Specifies a comment to be added with the database created.
  • options: You can specify command-line arguments accepted by createdb.

Options:

  • -D tablespace: It specifies the default tablespace for the database.
  • -e: It echo the commands that are generated and sent to the server by createdb command.
  • -E encoding: It specifies the character set encoding scheme to be used in the database created.
  • -l locale: It specifies the locale to be used in this database.
  • -T template: It specifies the template database from which the new database will be created.
  • -h host: It specifies the host name of the machine where the server is running.
  • -p port: It is used to specify the TCP port on which the server is listening for connections.
  • -U username: It is used to set the user name to connect as.
  • -w: It enables to never issue a password prompt.
  • -W: It forces createdb to prompt for a password before connecting to a database.
  • –help: It shows help/documentation about createdb command line arguments.

Examples:

postgres-# l
List the databases in Postgresql
List the databases in Postgresql
postgres=# createdb -h localhost -p 5432 -U postgres mydb3
postgres-# l
Creating a new database using createdb
Creating a new database using createdb and verifying it

How to create database in postgresql using pgadmin 4

Launch pgAdmin: Launching pgAdmin is easy. It is available in the respective application or programs folder for the operating system that you may be using. 

On Linux systems, pgAdmin is available under Programming in the Applications menu:

locating pgadmin in linux
Locating pgAdmin 4 in Linux

On Windows, pgAdmin is available under Program Files:

Locating pgAdmin 4 in Windows
Locating pgAdmin 4 in Windows

On a Mac, pgAdmin is available in the Applications folder as an application:

Locating pgAdmin 4 in Mac
Locating pgAdmin 4 in Mac
  • Connect to database server
  • Navigate through: Databases > Create > Database
create database using pgadmin
Create Database using pgadmin 4
  • In the pop-up window,
    • Enter Database Name
    • Enter Comment – It is optional to specify
    • Click Save
  • Done, Now you can see the newly created database in the Object Tree.

Postgresql create database

To create the database in Postgresql, we must be a superuser, follow the below syntax.

CREATE DATABASE name
    [ [ WITH ] [ OWNER [=] user_name ]
           [ TEMPLATE [=] template ]
           [ ENCODING [=] encoding ]
           [ LC_COLLATE [=] lc_collate ]
           [ LC_CTYPE [=] lc_ctype ]
           [ TABLESPACE [=] tablespace ]
           [ CONNECTION LIMIT [=] connlimit ] ]

The following is the parameter meaning of the above syntax.

  • name: It is a name of a database to create.
  • user_name: It is the role name of the user who is going to own the new database.
  • template: It is the name of the template from which to create the new database.
  • encoding: It is character set encoding to use in the new database. Specify a string constant (like ‘SQL_ASCII’), or an integer encoding number.
  • lc_collate: It is a collation order to be used in the new database.
  • lc_ctype: It is a character classification to be used in the new database. It affects the categorization of characters, like lower, upper, and digit.
  • tablespace: It is the name of the tablespace that is going to be associated with the new database.
  • connlimit: It’s about how many concurrent connections can be made to this database. By default is -1 which means no limit.

Postgresql create database command line

In Postgresql, we can create a database using the command line, follow the below instructions.

  • Open command prompt by Windows+R and then, type “cmd”, hit Enter.
  • Type the below command to enter into the Postgresql command prompt.
psql -U postgres 
--In the above code -U represents user,so we are goint to login as postgres user.
  • Create a database using the below statement.
CREATE DATABASE database_name;
  • Check the database using the l command that shows all the available databases.
l -- To list all the databases
Postgresql create database command line
Postgresql create database command line

From the above output, we see a newly created database named database_name.

Read: How to create a table in PostgreSQL

Postgresql create database and user

In Postgresql, first, we will create a new user then create a new database under that user.

Syntax:

CREATE USER user_name  WITH option

Whether we are on Windows (command-line) or Linux (terminal), the same command is used to create a user in Postgresql given below.

psql -U postgres -- To login as superuser or postgres that is superuser

Create a new user named sam with the password ‘12345’.

CREATE USER sam with encrypted password '12345';

then create a new database named sam_database.

CREATE DATABASE sam_database;

Grant access to a new user of a newly created database named sam_database, run the following statement.

GRANT ALL PRIVILEGES ON DATABASE sam_database TO sam;

verify the newly created user using the below command.

du  -- It is used to list all user
Postgresql create database and user
Postgresql create database and user

Read: How to connect to PostgreSQL database

Postgresql create database if not exists

In Postgresql, there is no command like if not exist but we have an alternative way to check the new database before creating it.

Postgresql has a system catalog named pg_database that contains information about all the databases. It is accessible from any database in the same database cluster.

Use the below command to a new create database.

SELECT 'CREATE DATABASE new_db'
WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = 'new_db')gexec

Here first, we are checking whether the database already exists in pg_database, if it does not exist, then it will create a new database named new_db.

gexec: It sends the current query buffer to the server, then considers each column of each row of the query’s output as a SQL statement to be executed.

Postgresql create database if not exists
Postgresql create database if not exists

In the above output, we have created a new database named new_db, before the creation of this database, we checked it into pg_database whether it already exists or not.

Read: How to Uninstall PostgreSQL

Postgresql create database command line ubuntu

In this sub-section, we are going to create a new Postgresql database on the Ubuntu operating system using the terminal (command-line).

  • Open a terminal by CTRL + ALT + T on Ubuntu and log into the Postgres prompt using the below command.
sudo -u postgres psql
  • To create a new database named ubuntu_database use the below statement.
CREATE DATABASE ubuntu_database;
Postgresql create database command line ubuntu
Postgresql create database command line ubuntu
  • Check the newly created database using the l command and execute the below statement.
l -- To list all the databases
Postgresql create database command line ubuntu
Postgresql create database command line ubuntu

From the above output, we have created a database named ubuntu_database on the command line ( terminal ).

Read: PostgreSQL WHERE

Postgresql create database with owner

In Postgresql, we can create a new database with a different owner, the owner is like a role that executed the creation statement. For almost all kinds of objects, the initial state is that only the owner can do anything with the object.

The following statement creates a new database named role_database with an owner named postgres.

CREATE DATABASE role_database WITH OWNER = postgres_user;

View the database with the owner using the below statement.

l --To list all daatabase with owner and other details
Postgresql create database with owner
Postgresql create database with owner

From the above output, we have created a new database named role_database and assigned an owner named postgres_user.

Read: PostgreSQL CASE

Postgresql create database not working

In Postgresql, if we get an error like create database not working, then check your syntax of creating database or what kind of permission user has, whether the user can create new database or not.

The correct syntax is given below to create a new database.

CREATE DATABASE db_name;

Where db_name is the name of the database that we want to create.

If the above solution doesn’t resolve your problem then, check the permission of the current user.

First, check the name of the current user.

SELECT current_user;

Then use the below statement to know the role attribute of the current user or permissions.

du
Postgresql create database not working
Postgresql create database not working

In the above output, first, we have found the current user, that is postgres, then we list all available users with their roles attributes. we found that postgres user has permission like Superuser, Create role, Create DB, etc.

if the current user has all the above roles attributes, then this user can create the database, if not then the user can’t create the database.

Read: PostgreSQL DATE Format

Postgresql create database link

In Postgresql, we can create a database remotely with the help of “dblink” that executes the query in a remote database.

Syntax:

dblink(text connname, text sql [, bool fail_on_error]) returns setof record

dblink(text connstr, text sql [, bool fail_on_error]) returns setof record

dblink(text sql [, bool fail_on_error]) returns setof record

The following is the meaning of the above argument with the dblink function.

  • connname: It is the name of the connection to use.
  • connstr: It is a connection info string.
  • SQL: It is the SQL query that we wish to execute in the remote database.
  • fail_on_error: It is the error, that is if true then an error thrown on the remote side of the connection causes an error to also be thrown locally. If it is false, then remote error is locally reported as a NOTICE, and the function returns no rows.

Let’s understand with an example, for this example, we will connect to a local database that also applies to the remote databases.

Create two separate databases in the Postgresql server running locally using statement.

CREATE DATABASE person_database_one;

CREATE DATABASE person_database_two;
Postgresql create database link
Postgresql create database link

Create a table and insert the following records in person_database_one.

c person_database_one -- connect to database

CREATE TABLE person(id int,name varchar(20),gender varchar(10));


INSERT INTO person(id,name,gender)VALUES(1,'Decker','Male'),
(2,'Lucifer','Male'),(3,'Dan','Male');
Postgresql create database link
Postgresql create database link

We are going to SELECT person_database_one data from person_database_two, so we have to execute all below scripts on person_database_two to configure the DbLink extension for cross-database queries.

Make a connection with person_database_two using the below command.

c person_database_two

Now install the dblink extension.

CREATE EXTENSION dblink;

Let’s verify the installed dblink system tables.

SELECT pg_namespace.nspname, pg_proc.proname 
FROM pg_proc, pg_namespace 
WHERE pg_proc.pronamespace=pg_namespace.oid 
   AND pg_proc.proname LIKE '%dblink%';
Postgresql create database link
Postgresql create database link

Check the connection with person_database_one.

SELECT dblink_connect('host=localhost user=postgres password=12345 dbname=person_database_one');

Make foreign data wrapper and the server for the global authentication, after that we can use this server object for cross-database queries.

CREATE FOREIGN DATA WRAPPER postgre VALIDATOR postgresql_fdw_validator;

CREATE SERVER demod_postgre FOREIGN DATA WRAPPER postgre OPTIONS (hostaddr '127.0.0.1', dbname 'person_database_one');

Mapping of user with server.

CREATE USER MAPPING FOR postgres SERVER demod_postgre OPTIONS (user 'postgres', password '12345');

Check the created server is ready or not by connecting to it.

SELECT dblink_connect('demod_postgre');
Postgresql create database link
Postgresql create database link

From the above output, we have successfully connected to a server named demod_postgre.

Now, we can SELECT the data of person_database_one from person_database_two.

SELECT * FROM dblink ('demod_postgre','SELECT id,name,gender FROM person') 
AS DATA(id INT,name VARCHAR(20),gender VARCHAR(10));
Postgresql create database link
Postgresql create database link

From the above output, we have created two databases and used the SELECT statement from person_database_two to data of person_database_one.

Read: PostgreSQL ADD COLUMN

Postgresql create database and table

In Postgresql, Let’s create a database and table under that database.

Use the below statement.

CREATE DATABASE employee; -- To create database

c employee  -- Connect to newly created database named employee
CREATE TABLE emp(id INT,emp_name VARCHAR(20),emp_role VARCHAR(30));
Postgresql create database and table
Postgresql create database and table

From the above output, we have created a database employee and table named emp.

Read: PostgreSQL vs SQL Server

Postgresql create database and schema

We are going to create a database and schema in Postgresql but before that, we need to know “What is schema?.”.

A schema is a namespace that contains named objects like tables, data types, functions, etc.

Syntax:

CREATE SCHEMA schema_name AUTHORIZATION user_name schema_element 

CREATE SCHEMA AUTHORIZATION user_name schema_element

CREATE SCHEMA IF NOT EXISTS schema_name AUTHORIZATION user_name 

CREATE SCHEMA IF NOT EXISTS AUTHORIZATION user_name

The following is the meaning of the above schema parameters.

  1. schema_name: It is the name of a schema to be created. If this is omitted, then the user_name is used as the schema name. The schema name cannot begin with pg_, because names are reserved for system schemas.
  2. user_name: It is the role name of the user who is going to own the new schema. If omitted, By defaults to the user executing the command.
  3. schema_element: It is an SQL statement which is used defining an object to be created within the schema. Currently, only CREATE TABLE, CREATE VIEW, CREATE INDEX, CREATE SEQUENCE, CREATE TRIGGER, and GRANT is accepted as clauses within CREATE SCHEMA.
  4. IF NOT EXISTS: It does nothing if a schema with the same name already exists.

Remember: To create a new schema, the invoking user should have the CREATE privilege for the current database.

The following statement creates a new schema in the current database.

CREATE DATABASE schema_database; -- Create new database named schema_database

c schema_database; -- Connect to schema_database

CREATE SCHEMA new_schema; -- To create new schema in the current database

dn -- To view schemas
Postgresql create database and schema
Postgresql create database and schema

From the above output, we have created a new database schema_database and schema named new_schema under that database.

Read: PostgreSQL ALTER TABLE

Postgresql create database and set owner

In Postgresql, we can change the ownership of any database using the below statement.

Let’s create a new database named owner_database and check the owner of the database.

CREATE DATABASE owner_database;

l -- to list all databases with ownership and other details
Postgresql create database and set owner
Postgresql create a database and set owner

From the above output, we have created a new database owner_database with the owner name postgres. There is also another database named jhony_database with the owner name jhony.

So our Postgresql database contains two kinds of owners named postgres and jhony.

Let’s change the owner of a newly created database named owner_database to the owner named jhony.

ALTER DATABASE owner_database OWNER TO jhony; -- to change the owner of database
Postgresql create database and set owner
Postgresql create database and set owner

In the above output, we have changed the owner of owner_database to an owner named jhony.

Read: PostgreSQL DATE Functions

Postgresql create database and role

In Postgresql, we are going to create a new role, and under that role, we will create a new database.

Enter into psql prompt using the below command.

psql -U postgres

Check current user or role using the below statement.

SELECT current_user; -- To show current user

Create a new role named jhony.

CREATE ROLE jhony WITH createdb; -- To create new role

Here createdb option allows the jhony role to create a new database;

Change the current role to a new role named jhony.

SET ROLE jhony;

Create a new database under this role.

CREATE DATABASE jhony_database;

Check the created database.

l -- To list all the databases
Postgresql create database and role
Postgresql create database and role

From the above output, we have created the database jhony_database under the role named jhony.

Here, we saw, Postgresql create database under different roles, owners, the schema of the Postgresql database.

You may like the following PostgreSQL tutorials:

  • PostgreSQL DATE Format + Examples
  • PostgreSQL WHERE IN with examples
  • How to Uninstall PostgreSQL (Linux, Mac, and Windows)
  • PostgreSQL WHERE with examples
  • Postgresql set user password
  • PostgreSQL CASE with Examples
  • How to Restart PostgreSQL (Linux, Windows, Mac)

In this PostgreSQL tutorial, we have learned How to create a database in Postgresql and have covered the below topic:

  • How to create database in postgresql
  • How to create database in postgresql in linux
  • How to create database in postgresql in windows
  • How to create database in postgresql in mac
  • How to create database in postgresql using psql
  • How to create database in postgresql using CREATE DATABASE
  • How to create database in postgresql using createdb
  • How to create database in postgresql using pgadmin 4
  • Postgresql create database command line
  • Postgresql create database and user
  • Postgresql create database if not exists
  • Postgresql create database command line ubuntu
  • Postgresql create database with owner
  • Postgresql create database not working
  • Postgresql create database link
  • Postgresql create database and table
  • Postgresql create database and schema
  • Postgresql create database and set owner
  • Postgresql create database and role

Bijay

I am Bijay having more than 15 years of experience in the Software Industry. During this time, I have worked on MariaDB and used it in a lot of projects. Most of our readers are from the United States, Canada, United Kingdom, Australia, New Zealand, etc.

Want to learn MariaDB? Check out all the articles and tutorials that I wrote on MariaDB. Also, I am a Microsoft MVP.

Installing PostgreSQL on Windows (WSL)

Prerequisites

  • OS version: Windows 10 Insider Preview build 18932 or later
  • Enable WSL 2 feature
  • Linux distro installed (e.g. Debian)
    • You can check it with wsl -l -v

Getting Started

Installing PostgreSQL

  1. Open your WSL terminal
  2. Update your Ubuntu sources:
  1. install PostgreSQL (and the -contrib package which has some helpful utilities) with:
sudo apt install postgresql postgresql-contrib

To manage or check the database service, use: sudo service postgresql #(status|start|stop)#

Examples:

sudo service postgresql status # for checking the status of your database
sudo service postgresql start # to start running your database
sudo service postgresql stop # to stop running your database

Setting Up postgres User

The default admin user, postgres, requires a password before you can connect to a database.

To set a password, use:

(you will get prompted to enter the password, type the characters, which won’t appear on screen, and press enter once finished)

Running psql Shell

psql is a terminal-based front-end for PostgreSQL. It lets you type in queries interactively, sending them to PostgreSQL, and returning the query results to you. Alternatively, input can be from a file.

# Start your postgres service with:
sudo service postgresql start

# Open the psql shell for the active postgresql service:
sudo -u postgres psql

To exit postgres=# enter: q or use the shortcut key: Ctrl + D

Creating Your First Database

(Reference for environment variable substitution)

bash-env-variables-postgresql-instructions

# Set a shell variable to currently logged in user
PSQL_MY_USERNAME=$(whoami)

# Create a new postgres user for the currently logged in user
sudo -u postgres createuser $PSQL_MY_USERNAME --superuser

# Create a new postgres database for the currently logged in user
sudo -u postgres createdb $PSQL_MY_USERNAME

# Assign SUPERUSER privileges to the database for your new user:

sudo -u postgres psql $PSQL_MY_USERNAME -c "ALTER USER $PSQL_MY_USERNAME WITH SUPERUSER"

Creating a New Database For an App

You shouldn’t use a root user outside of the Terminal, and this user should be blocked off from the internet.

Let’s create a separate user for each app, like this:

MY_APP_NAME=hello_world

sudo -u postgres createuser $MY_APP_NAME
sudo -u postgres createdb $MY_APP_NAME

sudo -u postgres psql $MY_APP_NAME -c "ALTER USER $MY_APP_NAME WITH SUPERUSER;"

And let’s check that our new user doesn’t have privileges to create or delete other databases:

# Enter psql shell
psql $MY_APP_NAME

Inside our psql shell, run: du to check the users. You should see something like this:

image

Troubleshooting

If you get the error PANIC: could not flush dirty data: Function not implemented, you can try this:

sudo nano /etc/postgresql/10/main/postgresql.conf

and append this line to the end of the file:

(Ctrl + O and press Y to save, and Ctrl + D to exit nano)

Resources

If you need help debugging problems, try: https://medium.com/@karansingh1559/how-to-set-up-postgresql-on-ubuntu-for-wsl-fcbb777d165b

  • Get started using MongoDB or PostgreSQL with Node.js on Windows
    • LICENSE of the Microsoft docs – Creative Commons Attribution

Like this post? Please share to your friends:
  • How to create boot usb windows
  • How to create bash script windows
  • How to create account windows 10
  • How to create a new folder in windows
  • How to copy photos from iphone to windows 10