How to Add Identity Column to Table Based on Order of Another Column
USE tempdb
GO
-- Create Table
CREATE TABLE TestTable (Col1 INT, Col2 VARCHAR(100))
GO
-- Insert Data
INSERT INTO TestTable (Col1, Col2)
VALUES (33, 'Ranjan');
INSERT INTO TestTable (Col1, Col2)
VALUES (22, 'shyam');
INSERT INTO TestTable (Col1, Col2)
VALUES (11, 'Tester');
GO
-- Select Data
SELECT *
FROM TestTable
GO
-- Add Identity Column
ALTER TABLE TestTable
ADD ID INT IDENTITY(1, 1)
GO
-- Select Data
SELECT *
FROM TestTable
GO
-- Clean up
DROP TABLE TestTable
GO
OR
USE tempdb
GO
-- Create Table
CREATE TABLE TestTable (Col1 INT, Col2 VARCHAR(100))
GO
-- Insert Data
INSERT INTO TestTable (Col1, Col2)
VALUES (33, 'Ranjan');
INSERT INTO TestTable (Col1, Col2)
VALUES (22, 'Shyam');
INSERT INTO TestTable (Col1, Col2)
VALUES (11, 'Tester');
GO
-- Select Data
SELECT *
FROM TestTable
GO
-- Create Clustered Index on Column ID
CREATE CLUSTERED INDEX IX_TestTable ON dbo.TestTable
(Col1 ASC)
GO
-- Add Identity Column
ALTER TABLE TestTable
ADD ID INT IDENTITY(1, 1)
GO
-- Select Data
SELECT *
FROM TestTable
GO
-- Clean up
DROP TABLE TestTable
GO
Is there any workaround to do the same?”
I quickly created clustered index in ASC order on Col1 and it ordered the table as expected and later added the identity column there. Let us see the script to get the desired result.
USE tempdb
GO
-- Create Table
CREATE TABLE TestTable (Col1 INT, Col2 VARCHAR(100))
GO
-- Insert Data
INSERT INTO TestTable (Col1, Col2)
VALUES (33, 'Ranjan');
INSERT INTO TestTable (Col1, Col2)
VALUES (22, 'Shyam');
INSERT INTO TestTable (Col1, Col2)
VALUES (11, 'Tester');
GO
-- Select Data
SELECT *
FROM TestTable
GO
-- Create Clustered Index on Column ID
CREATE CLUSTERED INDEX IX_TestTable ON dbo.TestTable
(Col1 ASC)
GO
-- Add Identity Column
ALTER TABLE TestTable
ADD ID INT IDENTITY(1, 1)
GO
-- Select Data
SELECT *
FROM TestTable
GO
-- Clean up
DROP TABLE TestTable
GO
Here is one more idea:
Step1 – Create temporary clustered index on “date time column in descending order”
CREATE CLUSTERED INDEX ix_YourTableTEMP ON YourTable (DateTimeColumn DESC)
Step2 – Add identity column. Now the IDs should be in order of previously created index – although I don’t think there is 100% guarantee on this.
ALTER TABLE YourTable ADD IdColumn INT IDENTITY(1,1)
Step3 – Drop temporary index
DROP INDEX ix_YourTableTEMP ON YourTable
Step4 – Create new clustered PK on new column
ALTER TABLE YourTable
ADD CONSTRAINT PK_YourTable PRIMARY KEY CLUSTERED (IdColumn)
Discover more from mycodetips
Subscribe to get the latest posts sent to your email.