We have this large table in our Postgres DB, let’s call it DataTable
with a decent amount of read/write operations.
There currently exists a unique constraint on this table that I would like to get rid of and instead replace it with a different unique constraint. I see that we can reduce the downtime of the table for index creation by using CONCURRENTLY
for index creation/deletion but is there a similar way to simulate DROP CONSTRAINT CONCURRENTLY
for a unique index?
If not, how can I remove this constraint safely?
2
Answers
In PostgreSQL, you cannot use DROP CONSTRAINT CONCURRENTLY. You can achieve what you want in two steps:
Create a new Constraint, and Alter the table to add that constraint.
Drop the already implemented Unique constraint.
If you don’t know the name of an already implemented UNIQUE constraint, you can get its auto-generated name through pg admin.
There is no need for a
CONCURRENTLY
clause when dropping a constraint, because that operation is always very fast.If you experience something else, that is because you have long running transactions on that table. Such transactions will block the
ACCESS EXCLUSIVE
lock thatALTER TABLE
needs on the table for a very short time. You will have to find a point in time when there is no long running transaction using the table.To avoid problems caused by waiting for a lock, use a technique like this:
If the statement is blocked for more than a second, it will terminate wiht an error. Keep repeating that until it succeeds.