39

I have simple table creating script in Postgres 9.1. I need it to create the table with 2-attributes PK only if it does not exist.

CREATE TABLE IF NOT EXISTS "mail_app_recipients"
(
    "id_draft" Integer NOT NULL,
    "id_person" Integer NOT NULL
) WITH (OIDS=FALSE); -- this is OK

ALTER TABLE "mail_app_recipients" ADD PRIMARY KEY IF NOT EXISTS ("id_draft","id_person");
-- this is problem since "IF NOT EXISTS" is not allowed.

Any solution how to solve this problem? Thanks in advance.

Pavel S.
  • 11,892
  • 18
  • 75
  • 113

3 Answers3

50

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;
Tom Gerken
  • 2,930
  • 3
  • 24
  • 28
  • 11
    It's important to notice that this code should be executed within `DO $$ BEGIN ... END $$;`, [see](https://www.postgresql.org/docs/current/plpgsql-control-structures.html) – artaxerx May 29 '20 at 10:34
22

You can try to DROP it before creating it (DROP has the IF EXISTS clause):

ALTER TABLE mail_app_recipients DROP CONSTRAINT IF EXISTS mail_app_recipients_pkey;
ALTER TABLE mail_app_recipients ADD CONSTRAINT mail_app_recipients_pkey PRIMARY KEY ("id_draft","id_person");

Note that this require that you give a name to the primary key constraint - in this example mail_app_recipients_pkey.

Jakub Kukul
  • 12,032
  • 3
  • 54
  • 53
22

Why not include the PK definition inside the CREATE TABLE:

CREATE TABLE IF NOT EXISTS mail_app_recipients
(
    id_draft Integer NOT NULL,
    id_person Integer NOT NULL,
    constraint pk_mail_app_recipients primary key (id_draft, id_person)
)