Restrictions

You can ask the system catalog pg_database - accessible from any database in the same database cluster. The tricky part is that CREATE DATABASE can only be executed as a single statement. The manual:

CREATE DATABASE cannot be executed inside a transaction block.

So it cannot be run directly inside a function or DO statement, where it would be inside a transaction block implicitly. SQL procedures, introduced with Postgres 11, cannot help with this either.

Workaround from within psql

You can work around it from within psql by executing the DDL statement conditionally:

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

The manual:

\gexec

Sends the current query buffer to the server, then treats each column of each row of the query's output (if any) as a SQL statement to be executed.

Workaround from the shell

With \gexec you only need to call psql once:

echo "SELECT 'CREATE DATABASE mydb' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = 'mydb')\gexec" | psql

You may need more psql options for your connection; role, port, password, ... See:

  • Run batch file with psql command without password

The same cannot be called with psql -c "SELECT ...\gexec" since \gexec is a psql meta‑command and the -c option expects a single command for which the manual states:

command must be either a command string that is completely parsable by the server (i.e., it contains no psql-specific features), or a single backslash command. Thus you cannot mix SQL and psql meta-commands within a -c option.

Workaround from within Postgres transaction

You could use a dblink connection back to the current database, which runs outside of the transaction block. Effects can therefore also not be rolled back.

Install the additional module dblink for this (once per database):

  • How to use (install) dblink in PostgreSQL?

Then:

DO

BEGIN
   IF EXISTS (SELECT FROM pg_database WHERE datname = 'mydb') THEN
      RAISE NOTICE 'Database already exists';  -- optional
   ELSE
      PERFORM dblink_exec('dbname=' || current_database()  -- current db
                        , 'CREATE DATABASE mydb');
   END IF;
END
;

Again, you may need more psql options for the connection. See Ortwin's added answer:

  • Simulate CREATE DATABASE IF NOT EXISTS for PostgreSQL?

Detailed explanation for dblink:

  • How do I do large non-blocking updates in PostgreSQL?

You can make this a function for repeated use.

Answer from Erwin Brandstetter on Stack Overflow
Top answer
1 of 12
269

Restrictions

You can ask the system catalog pg_database - accessible from any database in the same database cluster. The tricky part is that CREATE DATABASE can only be executed as a single statement. The manual:

CREATE DATABASE cannot be executed inside a transaction block.

So it cannot be run directly inside a function or DO statement, where it would be inside a transaction block implicitly. SQL procedures, introduced with Postgres 11, cannot help with this either.

Workaround from within psql

You can work around it from within psql by executing the DDL statement conditionally:

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

The manual:

\gexec

Sends the current query buffer to the server, then treats each column of each row of the query's output (if any) as a SQL statement to be executed.

Workaround from the shell

With \gexec you only need to call psql once:

echo "SELECT 'CREATE DATABASE mydb' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = 'mydb')\gexec" | psql

You may need more psql options for your connection; role, port, password, ... See:

  • Run batch file with psql command without password

The same cannot be called with psql -c "SELECT ...\gexec" since \gexec is a psql meta‑command and the -c option expects a single command for which the manual states:

command must be either a command string that is completely parsable by the server (i.e., it contains no psql-specific features), or a single backslash command. Thus you cannot mix SQL and psql meta-commands within a -c option.

Workaround from within Postgres transaction

You could use a dblink connection back to the current database, which runs outside of the transaction block. Effects can therefore also not be rolled back.

Install the additional module dblink for this (once per database):

  • How to use (install) dblink in PostgreSQL?

Then:

DO

BEGIN
   IF EXISTS (SELECT FROM pg_database WHERE datname = 'mydb') THEN
      RAISE NOTICE 'Database already exists';  -- optional
   ELSE
      PERFORM dblink_exec('dbname=' || current_database()  -- current db
                        , 'CREATE DATABASE mydb');
   END IF;
END
;

Again, you may need more psql options for the connection. See Ortwin's added answer:

  • Simulate CREATE DATABASE IF NOT EXISTS for PostgreSQL?

Detailed explanation for dblink:

  • How do I do large non-blocking updates in PostgreSQL?

You can make this a function for repeated use.

2 of 12
167

another alternative, just in case you want to have a shell script which creates the database if it does not exist and otherwise just keeps it as it is:

psql -U postgres -tc "SELECT 1 FROM pg_database WHERE datname = 'my_db'" | grep -q 1 || psql -U postgres -c "CREATE DATABASE my_db"

I found this to be helpful in devops provisioning scripts, which you might want to run multiple times over the same instance.

For those of you who would like an explanation:

-c = run command in database session, command is given in string
-t = skip header and footer
-q = silent mode for grep 
|| = logical OR, if grep fails to find match run the subsequent command
🌐
PostgreSQL
postgresql.org › docs › current › sql-createdatabase.html
PostgreSQL: Documentation: 18: CREATE DATABASE
May 14, 2026 - 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 ...
Discussions

mysql - DROP DATABASE IF EXISTS CREATE DATABASE IF NOT EXISTS USE in PostgreSQL - Database Administrators Stack Exchange
In PostgreSQL there are the following problems. IF NOT EXISTS is not definied, USE is not defined. Instead of this we can use \c but it doesn't work if I write it in executable sql file. Additionally I cant remove database If I am connected with this database. More on dba.stackexchange.com
🌐 dba.stackexchange.com
December 5, 2016
In PostgreSQL, I want to check for the existence of a database and user and perform a branch process
I want to execute the following query if the database and user does not exist. CREATE DATABASE database; CREATE ROLE user WITH LOGIN PASSWORD 'password'; REVOKE CONNECT ON DATABASE db1 FROM PUBLIC; GRANT CONNECT ON DATABASE db1dev TO userbdev; PostgreSQL does not allow IF NOT EXSIST in CREATE ... More on forum.golangbridge.org
🌐 forum.golangbridge.org
0
0
March 4, 2023
Can I create a new database when it does not exist by sqlalchemy?
I wonder if I can use sqlalchemy ... and if the database dosen't exist, I can use sqlalchemy to create that database? I tried to drop database name from uri, create engine from that name-dropped uri, and use engine.execute("CREATE DATABASE xxx"), but it would recognize my username as a database name and raise error in create_engine. Must I create new database manually? Beta Was this translation helpful? Give feedback. ... Every connection in postgresql needs to connect ... More on github.com
🌐 github.com
1
1
August 6, 2024
Postgres 9.3 feature highlight: IF EXISTS and IF NOT EXISTS
Postgres is getting mind-blowingly good. Ok, so this is just a small, cool new feature, but every major release adds a slew of these, and it's adding up to something pretty damn amazing. And, importantly, all the core functionality is rock solid. Postgres must be one of the top OSS projects in existence. I struggle to understand why anyone would want to use another relational database. /rampant fanboi-ism More on reddit.com
🌐 r/programming
81
212
May 26, 2013
🌐
DB Vis
dbvis.com › thetable › create-database-in-postgresql-a-complete-guide
CREATE DATABASE in PostgreSQL: A Complete Guide
April 30, 2025 - PostgreSQL does not provide a syntax for creating a database only if it does not already exist (like MySQL's CREATE DATABASE IF NOT EXISTS).
🌐
Zaiste
zaiste.net › databases › postgresql › howtos › create-database-if-not-exists
Create a database if not exists in PostgreSQL
SELECT 'CREATE DATABASE <your db name>' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = '<your db name>')\gexec · \gexec sends the current query buffer to the server, then treats each column of each row of the query's output (if any) as a SQL statement to be executed.
Top answer
1 of 2
1

There are two different ways of creating a database in PostgreSQL. One is from the command line. The other is from the PostgreSQL console.

Command Line

In order to be able to create a database from the command line, you must first change to a user with rights to create a database. As you have shown with the \du command above, the user with those rights is postgres.

root@eric-desktop:/home/eric# su postgres
postgres@eric-desktop:/home/eric$ createdb prismatest2
postgres@eric-desktop:/home/eric$

As you can see, the creatdb command does not give any feedback. You need to confirm the creation by listing the current databases:

psql -U postgres -l
                                                 List of databases
    Name     |  Owner   | Encoding |   Collate   |    Ctype    | ICU Locale | Locale Provider |   Access privileges   

-------------+----------+----------+-------------+-------------+------------+-----------------+-----------------------

 postgres    | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 |            | libc            | 

 prismatest  | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 |            | libc            | 

 prismatest2 | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 |            | libc            | 

PostgreSQL Console

Another possibility is to use the PostgreSQL console. To enter the console:

root@eric-desktop:/home/eric# sudo -u postgres psql psql (15.7 (Debian 15.7-0+deb12u1)) Type "help" for help.

postgres=# 
postgres=# CREATE DATABASE "prismatest3";
CREATE DATABASE
postgres=# 

To confirm the creation of the database, list the databases:

postgres=# \l

                                                 List of databases
    Name     |  Owner   | Encoding |   Collate   |    Ctype    | ICU Locale | Locale Provider |   Access privileges   

-------------+----------+----------+-------------+-------------+------------+-----------------+-----------------------

 postgres    | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 |            | libc            | 

 prismatest  | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 |            | libc            | 

 prismatest2 | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 |            | libc            | 

 prismatest3 | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 |            | libc            | 
2 of 2
3

Notice how the prompt has changed from the first line to the second:

        v
postgres=# createdb prismatest
postgres-# \l
        ^

psql is hinting that you are entering more lines of the same command.

Enter the semicolon (";") that terminates the create database statement.

postgres=# createdb prismatest ; 
🌐
Medium
medium.com › @aashisingh640 › node-js-postgresql-create-database-if-it-doesnt-exist-1a93f38629ab
Node.js + PostgreSQL — Create database if it doesn’t exist | by Aashi Singh | Medium
July 16, 2023 - If database doesn’t exist, we will create the database with the same name. const res = await client.query(`SELECT datname FROM pg_catalog.pg_database WHERE datname = '${DB_NAME}'`); if (res.rowCount === 0) { console.log(`${DB_NAME} database ...
Find elsewhere
🌐
w3resource
w3resource.com › PostgreSQL › snippets › postgresql-create-database-if-not-exists.php
How to Create a Database if not exists in PostgreSQL?
December 31, 2024 - Since PostgreSQL lacks the IF NOT EXISTS clause for database creation, you can use a combination of a conditional query and dynamic SQL within a block.
🌐
PostgreSQL
postgresql.org › docs › current › manage-ag-createdb.html
PostgreSQL: Documentation: 18: 22.2. Creating a Database
May 14, 2026 - In order to create a database, the PostgreSQL server must be up and running (see Section 18.3). Databases are created with the SQL command CREATE DATABASE: ... where name follows the usual rules for SQL identifiers.
🌐
Stack Exchange
dba.stackexchange.com › questions › 157283 › drop-database-if-exists-create-database-if-not-exists-use-in-postgresql
mysql - DROP DATABASE IF EXISTS CREATE DATABASE IF NOT EXISTS USE in PostgreSQL - Database Administrators Stack Exchange
December 5, 2016 - I always was used following header in files that defined database in MySql: DROP DATABASE IF EXISTS base; CREATE DATABASE IF NOT EXISTS base; USE base; In PostgreSQL there are the following
🌐
PostgreSQL
postgresql.org › message-id › MEYP282MB1669A5EEBC791F927D89063EB6009@MEYP282MB1669.AUSP282.PROD.OUTLOOK.COM
PostgreSQL: CREATE DATABASE IF NOT EXISTS in PostgreSQL
February 27, 2022 - When I try to use CREATE DATABASE IF NOT EXISTS in PostgreSQL, it complains this syntax is not supported.
🌐
Octopus Deploy
octopus.com › integrations › postgresql › postgres-create-database-if-not-exists
Postgres - Create Database If Not Exists | Octopus Integrations
May 23, 2024 - += \";Integrated Security=True;\"\n }\n }\n\n\t# Open connection\n Open-PostGreConnection -ConnectionString $connectionString -ConnectionName $connectionName\n\n # See if database exists\n $databaseExists = Get-DatabaseExists -DatabaseName $createDatabaseName\n\n if ($databaseExists.ItemArray.Count -eq 0)\n {\n # Create database\n Write-Output \"Creating database $createDatabaseName ...\"\n $executionResult = Invoke-SqlUpdate -Query \"CREATE DATABASE `\"$createDatabaseName`\";\" -CommandTimeout $postgresCommandTimeout -ConnectionName $connectionName\n\n # Check result\n if ($executionResult -n
🌐
DigitalOcean
docs.digitalocean.com › how do i fix the "database does not exist" error when connecting to postgresql?
How do I fix the "Database Does Not Exist" error when connecting to PostgreSQL? | DigitalOcean Documentation
March 18, 2026 - A Database Does Not Exist error ... to the wrong cluster: ... If you are getting this error, first verify that you are using the correct hostname to connect by following How to Connect to PostgreSQL Database Cluste...
🌐
Postgrespro
postgrespro.ru › list › thread-id › 2591329
Обсуждение: Re: CREATE DATABASE IF NOT EXISTS in PostgreSQL : Компания Postgres Professional
Hi, hackers When I try to use CREATE DATABASE IF NOT EXISTS in PostgreSQL, it complains this syntax is not supported. We can use the following command to achieve this, however, it's not straightforward. SELECT 'CREATE DATABASE mydb' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = ...
🌐
Go Forum
forum.golangbridge.org › getting help
In PostgreSQL, I want to check for the existence of a database and user and perform a branch process - Getting Help - Go Forum
March 4, 2023 - I want to execute the following query if the database and user does not exist. CREATE DATABASE database; CREATE ROLE user WITH LOGIN PASSWORD 'password'; REVOKE CONNECT ON DATABASE db1 FROM PUBLIC; GRANT CONNECT ON DATABASE db1dev TO userbdev; PostgreSQL does not allow IF NOT EXSIST in CREATE DATABASE like MySQL does, so I would like to do the branching on the application side, is there a better way?
🌐
CommandPrompt Inc.
commandprompt.com › education › postgresql-create-database-if-not-exists
PostgreSQL CREATE DATABASE IF NOT EXISTS — CommandPrompt Inc.
May 5, 2024 - You can use a subquery to create ... how to do it using the below syntax: SELECT 'CREATE DATABASE <db_name>' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = '<db_name>')\gexec...
Address   2950 Newmarket ST STE 101 - 231, 98226, Bellingham
🌐
GeeksforGeeks
geeksforgeeks.org › postgresql › postgresql-create-database
PostgreSQL - Create Database - GeeksforGeeks
July 12, 2025 - Creating a database in PostgreSQL can be done using the CREATE DATABASE SQL statement in the psql shell or via the createdb command-line utility. Additionally, for users who prefer a graphical interface, pgAdmin offers a convenient way to manage ...
🌐
PostgresAI
postgres.ai › blog › 20211103-three-cases-against-if-not-exists-and-if-exists-in-postgresql-ddl
Three cases against IF NOT EXISTS / IF EXISTS in Postgres DDL | PostgresAI
November 3, 2021 - For such time of mistakes, we do ... - bug IF EXISTS is going to "mask" the problem. As a result, automated testing is not going to catch the problem, and this wrong change has risks to be released. For large tables under load, it is recommended to use CREATE INDEX CONCURRENTLY – it is going to work longer that CREATE INEDEX but it won't cause downtime. It is not uncommon to see how DBAs try various index ideas right on the production database, trying to ...
🌐
DataCamp
datacamp.com › doc › postgresql › create-database
PostgreSQL CREATE DATABASE
The `CREATE DATABASE` command is used to create a new database within the PostgreSQL system.