Postgresql – the best way to create Primary Key on a large table in Postgresql 9.5

ddlpostgresqlpostgresql-9.5

I have to create a primary key on a large table (~100Million records) in Postgtres database. What is the best and fastest way to create pkey? This column is a sequence column and i don't want to lock the table because this is highly transactional database.

Best Answer

You can create a unique index with the option concurrently which will allow read and write access to the table while the index is created. However, building an index concurrently will take much longer then adding the index without that option.

create unique index concurrently unique_id on the_big_table (id);

Once the index is created, you can use that as a primary key:

alter table the_big_table
   add primary key using index unique_id;

That will only lock the the table for a very short time.