Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgresql: how to create table only if it does not already exist?

In Postgresql, how can I do a condition to create a table only if it does not already exist?

Code example appreciated.

like image 615
Fredriku73 Avatar asked Jan 12 '09 13:01

Fredriku73


People also ask

How do you CREATE TABLE if not exists in Postgres?

Use the CREATE TABLE statement to create a new table. Use the IF NOT EXISTS option to create the new table only if it does not exist. Apply the primary key, foreign key, not null, unique, and check constraints to columns of a table.

Does Postgres create database if not exists?

Unlike MySQL, PostgreSQL does not support create if not exists syntax.


2 Answers

I'm not sure when it was added, but for the sake of completeness I'd like to point out that in version 9.1 (maybe before) IF NOT EXISTS can be used. IF NOT EXISTS will only create the table if it doesn't exist already.

Example:

CREATE TABLE IF NOT EXISTS users.vip (   id integer ) 

This will create a table named vip in the schema users if the table doesn't exist.

Source

like image 189
Skalli Avatar answered Sep 25 '22 12:09

Skalli


create or replace function update_the_db() returns void as $$ begin      if not exists(select * from information_schema.tables          where              table_catalog = CURRENT_CATALOG and table_schema = CURRENT_SCHEMA             and table_name = 'your_table_name_here') then          create table your_table_name_here         (             the_id int not null,             name text         );      end if;  end; $$ language 'plpgsql';  select update_the_db(); drop function update_the_db(); 
like image 36
Michael Buen Avatar answered Sep 25 '22 12:09

Michael Buen