Constraint name update in PostgreSQL

PostgresqlConstraints

Postgresql Problem Overview


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!

Postgresql Solutions


Solution 1 - Postgresql

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;

Solution 2 - Postgresql

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)

Solution 3 - Postgresql

We found that primary keys often lag behind the main table name. This script helped us identify and fix the ones with issues.

select 
    table_name, 
    constraint_name , 
    'ALTER TABLE ' || table_name || ' RENAME CONSTRAINT ' || constraint_name || ' TO ' || left(table_name, 58) || '_pkey;'
from information_schema.table_constraints tc
where constraint_type  = 'PRIMARY KEY' 
and constraint_name <> left(table_name, 58) || '_pkey';

This finds all the tables where the primary key name is no longer the "default" pattern (<tablename>_pkey) and creates a rename script for each.

The 58 character limit above in code above is to account for the maximum size of constraint names (63bytes).

Obviously sense check what is returned prior to running it. Hope that is helpful for others.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSebastianView Question on Stackoverflow
Solution 1 - PostgresqlArturo HerreroView Answer on Stackoverflow
Solution 2 - PostgresqlMagnus HaganderView Answer on Stackoverflow
Solution 3 - PostgresqlPaul GrimshawView Answer on Stackoverflow