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
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.
<> is the standard SQL operator meaning "not equal". Many databases, including postgresql, supports != as a synonym for <> . They're exactly the same in postgresql.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With