0

I want to create a Primary Key on a table with 6 Million records, but when I execute this:

ALTER TABLE schema_name.table_name ADD CONSTRAINT pkey_name PRIMARY KEY (field_pkey_name);

It's locking my table and alter table does not finish executing...

davidleongz
  • 155
  • 2
  • 11
  • If it doesn't ever finish, then it must be blocked by something else holding a conflicting lock. You will probably need to resolve this before any method is going to work. Laurenz's method only needs a strong lock for a fraction of a second, but it still does need to take a strong lock. – jjanes Jan 07 '21 at 16:44

1 Answers1

8

Try to do it in two steps:

CREATE UNIQUE INDEX CONCURRENTLY pkey_name
   ON schema_name.table_name (field_pkey_name);

ALTER TABLE schema_name.table_name
   ADD CONSTRAINT pkey_name PRIMARY KEY USING INDEX pkey_name;

It will still take a long time (even longer), but the table will not be locked for a long time.

Laurenz Albe
  • 209,280
  • 17
  • 206
  • 263