Postgres database create if not exists

20,144

No but you could query the pg_catalog.pg_database table to see if it exists.

Share:
20,144
Konstantin Tarashchanskiy
Author by

Konstantin Tarashchanskiy

MTS 3, Product Analytics at VMware

Updated on August 23, 2020

Comments

  • Konstantin Tarashchanskiy
    Konstantin Tarashchanskiy over 3 years

    Is there an analog to CREATE TABLE IF NOT EXISTS for creating databases?

    Background: I am writing a script to automatically set up the schema in PostgreSQL on an unknown system. I am not sure if the database (or even part of the schema) was already deployed, so I want to structure my code to not fail (or ideally even show errors) if some of the structure already exists. I want to differentiate the errors that prevent me from creating a database (so abort future schema changes since they will not work) from this error.

  • ahanin
    ahanin over 10 years
    You need to do this in function then, and this wouldn't work in 9.3, because Postgres doesn't allow to create/drop databases from inside function or multi-command string.
  • Eelke
    Eelke over 10 years
    But you could write an external script in php, python, perl or whatever you favour.
  • Enwired
    Enwired about 10 years
    Wouldn't it be simpler to just use DROP TABLE IF EXISTS "foo"; CREATE TABLE "foo";
  • Steve Midgley
    Steve Midgley over 9 years
    @Enwired - what if you don't want to drop the existing table if it exists? You might want to create it if it doesn't exist, but leave it alone if it does.
  • Enwired
    Enwired over 9 years
    If that is what you want, then the commands I specified wouldn't be useful for you. The original question was actually about creating a database, not a table, so my comment was accidentally off-topic anyway! Sorry.