Constraint name update in PostgreSQL

Is it possible to change the constraint name in Postgres? I have a PK added with:

ALTER TABLE contractor_contractor ADD CONSTRAINT commerce_contractor_pkey PRIMARY KEY(id);

And I want to to have different name for it, to be consistent with the rest of the system. Shall I delete the existing PK constraint and create a new one? Or is there a 'soft' way to manage it?

Thanks!


To rename an existing constraint in PostgreSQL 9.2 or newer, you can use ALTER TABLE:

ALTER TABLE name RENAME CONSTRAINT constraint_name TO new_constraint_name;

For the primary key, you should be able to just:

ALTER INDEX commerce_contractor_pkey RENAME TO whatever_new_name

That won't work for other types of constraints though. The best option there is to drop the old one and create a new one. Be sure to do it inside a transaction, so the system isn't live without it during rebuild. (And if you can't do it in a transaction, be sure to create the new one first, before dropping the old one)