In Postgresql, how can I do a condition to create a table only if it does not already exist?
Code example appreciated.
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.
Unlike MySQL, PostgreSQL does not support create if not exists syntax.
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
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With