Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server auto increment a column without primary key

Tags:

sql

sql-server

Is it possible to auto increment a column in SQL Server WITHOUT it being a primary key?

If yes how can this be done.

Thanks

like image 520
Bruce Avatar asked Sep 14 '11 14:09

Bruce


1 Answers

Yes. There is no requirement that IDENTITY columns be made a primary key.

CREATE TABLE T
(
X INT PRIMARY KEY,
Y INT IDENTITY(1,1)
)

Though I'm not sure when this would be useful. If you have a natural key that you want to use as the PK then you would probably want to put a unique constraint on the surrogate alternate key anyway.

For purposes of setting up FK relationships SQL Server doesn't care if the column(s) is the PK or not it just requires a unique index on it/them.

like image 130
Martin Smith Avatar answered Sep 29 '22 11:09

Martin Smith