title: "Create database if not exists" in postgres
body: <p>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. </p>
  
  <p>The following script in postgreSQL throws an error saying, "CREATE DATABASE cannot be executed from a function or multi-command string"</p>
  
  <pre><code>do $$
  begin
  If not exists (select 1 from pg_database where datname = 'TestDB')
  Then
   CREATE DATABASE "TestDB";
  end if;
  end
  $$
  </code></pre>
  
  <p>I created a postgres database dump file by exporting a backup of the database but that contains,</p>
  
  <pre><code>Drop Database "TestDB"
  
  Create Database "TestDB"
  </code></pre>
  
  <p>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.</p>
  
  <p>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? </p>
  
  <p>Thanks in Advance </p>