Add PRIMARY KEY constraint to existing table

Viewed 2707

I backed up and recovered 2 weeks ago and all primary keys and foreign keys were disabled. How can I change it?

I'm using Django btw. Unfortunately, I have no idea about DB.

enter image description here

1 Answers

Use ALTER TABLE:

ALTER TABLE user_user_user_permissions
ADD CONSTRAINT user_user_user_permissions_id_pkey PRIMARY KEY (id);

Of course, data in the id column must be UNIQUE and NOT NULL, or you get an exception trying.

If a different PRIMARY KEY constraint exists, drop that first:

ALTER TABLE user_user_user_permissions
  DROP CONSTRAINT old_constraint_name
, ADD CONSTRAINT user_user_user_permissions_id_pkey PRIMARY KEY (id);

You can look up the name of the existing constraint in pgAdmin under "Constraints" like you show in the picture.

Related