I've seen lots of information around adding a new primary key column to a large database table, but I have a somewhat different situation.
I have a large table (~90,000,000 records), that has no primary key. However, it DOES have a "RowID" column, which is an identity column. It also has a unique index on the RowID column.
All my research showed that a table without a primary key is terrible design that should be gotten rid of if at all possible. In my particular case; it's causing issues because Entity Framework maps the table as a read only view if it can't find a primary key.
I want to add a primary key constraint to the table on the RowID column. I was hoping that because it's not adding a new column, and there's already a unique index on that column, that it would be a small operation; however, it appears from a test run that it will take a very long time.
Having this table be inaccessible for a long time will cause issues across our business. I know that another option is to create a new table with the new schema, and copy all data from the old to the new. But this will also cause us to need to lock down the table for a long time.
Is there a way to more quickly add the primary key constraint when you already have an identity column with a unique index?
CREATE TABLE
script in the question and whether that UNIQUE index is clustered or not. Adding a PRIMARY KEY to a heap table would convert the table to clustered. (unless you specify nonclustered in the create index.) So, it much depends on what the goal is (keep it as heap or not), besides the other point by Aaron.ALTER TABLE ... SWITCH
allows you to go from a unique index to a unique constraint. But neither of these allow you to switch to a PK constraint - even when the column is not nullable and the supporting index has the same clustered/nonclustered specification. But it looks like you don't need to do this anyway stackoverflow.com/a/4000659/73226