Postgres database create if not exists
20,144
No but you could query the pg_catalog.pg_database table to see if it exists.
Comments
-
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 over 10 yearsYou 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 over 10 yearsBut you could write an external script in php, python, perl or whatever you favour.
-
Enwired about 10 yearsWouldn't it be simpler to just use DROP TABLE IF EXISTS "foo"; CREATE TABLE "foo";
-
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 over 9 yearsIf 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.