14

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.

0

1 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

5 Comments

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.
But you could write an external script in php, python, perl or whatever you favour.
Wouldn't it be simpler to just use DROP TABLE IF EXISTS "foo"; CREATE TABLE "foo";
@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.
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.