SQL

How To Create Auto Increment Field Using Query In SQL

In this article, we will learn how to create an auto-increment field/column using a query in SQL.

The IDENTITY keyword is used to perform an auto-increment feature in MS SQL Server.

The auto-increment allows a unique number to be generated automatically when a new record is inserted into a table.

Often this is the primary key field that we would like to be created automatically, whenever a new record is inserted.

Syntax

CREATE TABLE TABLE_NAME (
    column1 datatype IDENTITY(1,1) PRIMARY KEY,
    column2 datatype,
    ....
    columnN datatype
);

Example

The subsequent statement would define the “ID” column as an auto-increment primary key field in the “Article” table:

CREATE TABLE Article (
    ID int IDENTITY(1,1) PRIMARY KEY,
    Title varchar(100)
);

Here, The starting value for IDENTITY is 1, and it will increment by 1 for each new record. To specify that the “ID” column should start at value 100 and increment by 2, change it to IDENTITY(100,2).

We will not have to specify a value for the “ID” column, to insert a new record into the “Article” table:

Please check How To Write Insert Query In SQL, to get a brief description of the INSERT INTO statement.

Example (INSERT)

The subsequent statement would insert a new record into the “Article” table with a unique value in the “ID” column:

INSERT INTO Article (Title) 
VALUES ('Introduction');

--OR--

INSERT INTO Article VALUES ('Introduction');

 

Also, check How To Create Index Using Query In SQL

Yasin Panwala

Yasin Panwala is a Web Developer and Author at TheCodeHubs. He has experience in Web Developing and Designing and also in Writing. He has got his skills in working on technologies like .NET Core, ADO.NET, AJAX, Angular, AngularJS, ASP.NET, ASP.NET MVC, Bootstrap, C#, CSS, Entity Framework, Express.js, GraphQL, HTML, JavaScript, JQuery, JSON, LINQ, Microsoft Office, MongoDB, MySQL, Node.js, PostgreSQL, SQL, SQL Server, TypeORM, TypeScript, Visual Basic .NET, Web API. He also got his skills in working with different integration and some known versioning tools. He is always ready to learn new things and he always tries his best on tasks that are assigned to him and gives the best possible outputs.

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

2 years ago