Add primary key to PostgreSQL table only if it does not exist

You could do something like the following, however it is better to include it in the create table as a_horse_with_no_name suggests.

if NOT exists (select constraint_name from information_schema.table_constraints where table_name="table_name" and constraint_type="PRIMARY KEY") then

ALTER TABLE table_name
  ADD PRIMARY KEY (id);

end if;

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)