This article is half-done without your Comment! *** Please share your thoughts via Comment ***
This is a common interview question for SQL Server Database Developer. SQL Database Developer must prepare for this.
Sequence and identity, both used to generate an auto number, but the major difference is Identity is a table dependant and Sequence is independent of a table.
A Sequence Object introduced in SQL Server 2012 and Identity column introduced in SQL Server 6.0.
A Sequence is a User defined object and Identity column is a table property.
The same Sequence object can use with the multiple tables. The same Identity column cannot use with multiple tables, we can define identity column on each table individually.
If you define the same Sequence Object to multiple tables, it generates the sequence number database-wide and maintains a unique sequence number across the multiple tables. An Identity column generates a unique number at table only.
Sequence syntax (Start with 1 and Increment by 1):
12345 CREATE SEQUENCEdbo.Sequence_Name AS INTSTART WITH 1INCREMENT BY 1GOIdentity syntax (Start with 1 and Increment by 1):
1234 CREATE TABLE dbo.Table_Name( Id INT IDENTITY(1,1),Name VARCHAR(50) )GO
Check the next value of Sequence object:
1 SELECT (NEXT VALUE FOR dbo.Sequence_Name) AS SeqNextValueCheck the next value of Identity Column:
(write after use of Identity column)
1 SELECT SCOPE_IDENTITY()
Check the current value of Sequence Object:
123 SELECT Current_ValueFROM Sys.SequencesWHERE name='Sequence_Name'Check the current value of Identity Column:
12 SELECT IDENT_CURRENT('Table_Name')AS 'IdentityCurrentValue'
You can modify a Sequence object using ALTER Statement.
1234 ALTER SEQUENCE dbo.Sequence_NameRESTART WITH 100INCREMENT BY 5GOYou can only reset the value of an Identity column using DBCC CHECKIDENT().
1 DBCC CHECKIDENT('Table_Name', RESEED,100)
In Sequence New values can be generated in an UPDATE statement, but in Identity new value cannot be generated in an UPDATE statement.
You can define a maximum value for Sequence Object (Using MAXVALUE). You cannot provide a maximum value to Identity Column.
Once your Sequence object reached to MAXVALUE, you can also define a CYCLE option to restart it from the beginning. You cannot restart an Identity column value.
You can also enable data CACHE for a Sequence Object. You cannot enable data CACHE for an Identity Column and it uses table related data cache.
A User must require an access permission for Sequence Object. For Identity column, User requires only table related permissions.
Performance wise, Identity column is 3x faster than Sequence object.
Leave a Reply