Take the 2-minute tour ×

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.

share|improve this question

1 Answer 1

up vote 1 down vote accepted

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

share|improve this answer
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. –  ahanin Oct 12 '13 at 17:39
But you could write an external script in php, python, perl or whatever you favour. –  Eelke Feb 3 at 13:04
Wouldn't it be simpler to just use DROP TABLE IF EXISTS "foo"; CREATE TABLE "foo"; –  Enwired Apr 14 at 23:14
@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. –  Steve Midgley Dec 4 at 20:00
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. –  Enwired Dec 5 at 22:10

Your Answer


