Archive for October, 2014

Postgres: Create table if it doesn’t already exist

Friday, October 24th, 2014

I have a script that uploads a series of data into tables and occasionally I have an alternate table that is not part of my company template so I need to create the table at run time.  I do not want try to create the table if it exists already.  I also did not want to have to write a table check query and run that separately each time.

I looked into creating a function to do this but I found that with the release of Postgres 9.1 there was an addition of the “if exists” or in my case, “if not exists” that allowed me to run one query that would only create the table if the table does not exist already.

CREATE TABLE IF NOT EXISTS {schema}.{table_name}

(

sku character varying(100) not null,

product_image character_varying(300) not null

);