Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Create database if not exists" in postgres

I am new to postgreSQL and I am trying to create a schema file which will contain all the scripts required to create the database and required tables. The way I used to do this for SQl server was to check if the database exists and then run the necessary scripts.

The following script in postgreSQL throws an error saying, "CREATE DATABASE cannot be executed from a function or multi-command string"

do $$
begin
If not exists (select 1 from pg_database where datname = 'TestDB')
Then
 CREATE DATABASE "TestDB";
end if;
end
$$

I created a postgres database dump file by exporting a backup of the database but that contains,

Drop Database "TestDB"

Create Database "TestDB"

which means everytime I run the schema file, the database would be dropped and recreated and it would be a problem if there is data present in the database.

How do I check if the database exists in postgreSQL without having to drop the database and recreate it everytime I run the file please?

Thanks in Advance

like image 408
Sugan88 Avatar asked Oct 01 '18 11:10

Sugan88


People also ask

Is not exists Postgres?

PostgreSQL EXISTS examples The NOT EXISTS is opposite to EXISTS . It means that if the subquery returns no row, the NOT EXISTS returns true. If the subquery returns one or more rows, the NOT EXISTS returns false.

What does <> mean in PostgreSQL?

<> is the standard SQL operator meaning "not equal". Many databases, including postgresql, supports != as a synonym for <> . They're exactly the same in postgresql.


1 Answers

For 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

Answer credit andreasl from this question.

like image 53
kooskoos Avatar answered Sep 30 '22 20:09

kooskoos