Search code examples
sql-serversql-server-2008primary-keyalter-table

SQL Server add auto increment primary key to existing table


As the title, I have an existing table which is already populated with 150000 records. I have added an Id column (which is currently null).

I'm assuming I can run a query to fill this column with incremental numbers, and then set as primary key and turn on auto increment. Is this the correct way to proceed? And if so, how do I fill the initial numbers?


Solution

  • No - you have to do it the other way around: add it right from the get go as INT IDENTITY - it will be filled with identity values when you do this:

    ALTER TABLE dbo.YourTable
       ADD ID INT IDENTITY
    

    and then you can make it the primary key:

    ALTER TABLE dbo.YourTable
       ADD CONSTRAINT PK_YourTable
       PRIMARY KEY(ID)
    

    or if you prefer to do all in one step:

    ALTER TABLE dbo.YourTable
       ADD ID INT IDENTITY
           CONSTRAINT PK_YourTable PRIMARY KEY CLUSTERED