SQL IDENTITY (Auto increment) – Automatic value increase, description

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];

IDENTITY-příklad

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).

identity-po-truncate-table

Rate this post
Category: SQL Commands Useful SQL Scripts

About Ing. Jan Zedníček - Data Engineer & Controlling

My name is Jan Zednicek, and I have been working as a freelance Data Engineer for roughly 10 years. During this time, I have been publishing case studies and technical guides on this website, targeting professionals, students, and enthusiasts interested in Data Engineering particularly on Microsoft technologies as well as corporate finance and reporting solutions. 🔥 If you found this article helpful, please share it or mention me on your website or Community forum

Leave a Reply

Your email address will not be published. Required fields are marked *