简体   繁体   中英

Create a Primary Key on a large table (6Million records) without locking the table in PostgreSQL

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...

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM