IDENTITY is a property in SQL Server that allows for the automatic numbering of records inserted into a table. It creates an automatic increment with unique values without the need for manual insertion of numbers into the table. This function can be utilized with numeric data types, and its typical use is for identifiers and primary keys. Automatic numbering can also be achieved through other methods, such as the SEQUENCE command, which I described in the linked article.
IDENTITY Syntax
Identity is attached as a column property, for example, when creating an SQL table, and the command has two arguments:
IDENTITY (<initial value>, <increment>)
- Initial value – is the value from which numbering starts. Typically, we might want to start from 1, but it is possible to start numbering from any value.
- Increment – is the number by which it will increment.
Example of Creating a Column with the SQL IDENTITY Function
A typical use case would be as follows:
Table Creation
CREATE TABLE [dbo].[Test_Identity] (
[ID] INT IDENTITY (1,1) PRIMARY KEY,
[Hodnota] VARCHAR(255) NOT NULL
);
Inserting Records and Checking the Numbering
Note that we are inserting values only, not IDs; the numbering is done automatically.
INSERT INTO [dbo].[Test_Identity] ([Hodnota])
VALUES (‘One’),(‘Two’),(‘Three’),(‘Four’);
SELECT * FROM [dbo].[Test_Identity];
Testing the Column Numbering in the Table
If you perform a TRUNCATE (clearing values) operation on the table and then refill it, the records will be renumbered from 1 to 4. This differs from the SEQUENCE, which is an object that remembers the last issued value and returns the next value. If you were to use SEQUENCE, you would get numbers 5 to 8 (or you would have to reset the sequence).