snippetsqlMajor
What is the best way to create Primary Key on a large table in Postgresql 9.5?
Viewed 0 times
postgresqltheprimarycreatewhatwaylargetablekeybest
Problem
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.
Solution
You can create a unique index with the option
Once the index is created, you can use that as a primary key:
That will only lock the the table for a very short time.
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.
Code Snippets
create unique index concurrently unique_id on the_big_table (id);alter table the_big_table
add primary key using index unique_id;Context
StackExchange Database Administrators Q#147255, answer score: 22
Revisions (0)
No revisions yet.