How to Create Id with AUTO_INCREMENT in SQL Server?
Last Updated :
18 Mar, 2024
Structured Query Language also known as SQL is a tool for storing, managing, and manipulating relational databases. SQL Server is a popular relational database management system (RDBMS) developed by Microsoft, providing a variety of operators to perform different operations on given datasets.
In this we will explore SQL's AUTO_INCREMENT, exemplifying its usage in tables like Employees, Products, and Customers, ensuring unique identifiers for each record.
AUTO_INCREMENT in SQL Server
The AUTO_INCREAMENT functionality in SQL is used to automatically increase a value for a particular column in the given row. It inserts the next value which is inserted in the last row. This is generally used to manage the serial numbers of the entries in the table or to assign an ID to each row.
It makes the column ideal for the primary key or situations where we need unique identifiers. In this article, we will see how to assign a column as AUTO_INCREAMENT.
Syntax to create an auto-increment column:
CREATE TABLE TableName (
ColumnName INTEGER PRIMARY KEY AUTOINCREMENT,
-- Other columns
);
Here ColumnName will be the name of that particular column and the PRIMARY KEY defines that the given column is the primary key of the table. The keyword AUTOINCREMENT will declare the column as incrementing automatically. We will perform the following steps to implement this.
- Declare the table structure.
- In structure declare a column as Primary Key and Auto Increment.
- Insert the data into the table.
- Print the table.
Examples of AUTO_INCREMENT in SQL Server
Example 1: Employees table with EmployeeID is auto increment
CREATE TABLE Employees (
EmployeeID INTEGER PRIMARY KEY AUTOINCREMENT,
FirstName VARCHAR(50),
LastName VARCHAR(50)
);
Now we will insert the data into this table.
INSERT INTO Employees (FirstName, LastName)
VALUES
('John', 'Doe'),
('Jane', 'Smith'),
('Michael', 'Johnson'),
('Emily', 'Davis');
When we insert this values they will get inserted into the table with the employee id.
Output:
Output TableExplanation: The provided SQL script is not valid for SQL Server. However, assuming it's meant for a database system like SQLite, the AUTOINCREMENT keyword automatically generates unique values for the EmployeeID column, ensuring each record has a distinct identifier.
Example 2: Products table with ProductID as Auto Increment
CREATE TABLE Products (
ProductID INTEGER PRIMARY KEY AUTOINCREMENT,
ProductName VARCHAR(50),
Price DECIMAL(10, 2),
StockQuantity INT
);
Now we will insert the data into this table.
INSERT INTO Products (ProductName, Price, StockQuantity)
VALUES
('Smartphone', 699.99, 100),
('Laptop', 1299.99, 50),
('Headphones', 99.99, 200),
('Smart Watch', 249.99, 150);
When we insert this values they will get inserted into the table with the product id.
Output:
Output TableExplanation: The provided SQL script creates a Products table with a primary key ProductID set to AUTOINCREMENT. The subsequent INSERT statements add records with unique ProductID values automatically generated by the system, ensuring each product entry has a distinct identifier.
In the resulting table ProductName, Price, and StockQuantity are added with Sequential ProductID.
Example 3: Customer table with CustomerID as Auto Increment
CREATE TABLE Customers (
CustomerID INTEGER PRIMARY KEY AUTOINCREMENT,
FirstName VARCHAR(50),
LastName VARCHAR(50),
Email VARCHAR(100),
Phone VARCHAR(20)
);
Now we will insert the data into this table.
INSERT INTO Customers (FirstName, LastName, Email, Phone)
VALUES
('Alice', 'Smith', '[email protected]', '123-456-7890'),
('Bob', 'Johnson', '[email protected]', '234-567-8901'),
('Charlie', 'Davis', '[email protected]', '345-678-9012'),
('David', 'Brown', '[email protected]', '456-789-0123');
When we insert this values they will get inserted into the table with the customer id.
Output:
Output TableExplanation: The provided SQL script creates a Customers table with a primary key CustomerID set to AUTOINCREMENT. The subsequent INSERT statements add records with unique CustomerID values automatically generated by the system, ensuring each customer entry has a distinct identifier.
In the resulting table FistName, LastName, Email, and Phone are added with sequential CustomerID.
Conclusion
Structured Query Language also known as SQL is a tool for storing, managing, and manipulating relational databases. SQL is a relational database used to store structured data. SQL uses commands to perform CRUD operations on the database tables. One of such command is AUTO_INCREAMENT which is a functionality used to automatically increase a value for a particular column in the given row. It is mostly used where we are inserting some data and want to assign a unique number or a unique id to each row in the table. It is useful in many places like managing employee data, product data, and user data.
Similar Reads
How to Create id With AUTO_INCREMENT in PL/SQL?
PL/SQL, short for Procedural Language/Structured Query Language, combines SQL capabilities with procedural programming. It supports variable declaration, control flow structures, functions, records, cursors, procedures, and triggers. PL/SQL features a block structure with optional sections for varia
5 min read
How to Create id with AUTO_INCREMENT in MySQL?
Primary keys in databases uniquely identify each record, ensuring data integrity and efficient retrieval. AUTO_INCREMENT, a feature in MySQL, automatically assigns unique numeric identifiers to new rows, simplifying data management. Understanding these concepts is crucial for designing robust databa
6 min read
How to Reset Auto Increment Counter in PostgreSQL?
PostgreSQL is a powerful, open-source, object-relational database management system (DBMS) developed by a vibrant community. One common requirement for database administrators is resetting the auto-increment counter for primary key sequences. In PostgreSQL, this process is crucial for ensuring the o
4 min read
How to Insert If Not Exists in SQL SERVER?
Adding Data to a table in SQL Server is a key operation. Data can be inserted into tables using many different scenarios like plain data inserted into a table without checking anything or checking if data already exists in the target table and only if the data does not exist then the new data is ins
7 min read
How to Reset Auto Increment in MySQL
Resetting the AUTO_INCREMENT value is a common operation, often required during development, testing, or database maintenance. We use the ALTER TABLE statement to reset the AUTO_INCREMENT property in MySQL. We can also use the TRUNCATE TABLE statement or use the DROP TABLE and CREATE TABLE statement
3 min read
How to Create a Composite Primary Key in SQL Server?
In this article, We will learn what is a Composite Primary Key and How will create a Composite Primary Key. As We know a Primary key is the Candidate key that is selected to uniquely identify a row in a table. A And Primary Key does not allow NULL value. Composite Primary KeyWhen two or more Columns
3 min read
How to Create Login, User and Grant Permissions in SQL Server
Managing logins, users and permissions in SQL Server is a critical aspect of database security and administration. This process ensures that only authorized individuals have access to the database and can perform necessary operations. In this article, we will learn how to create and manage logins, a
5 min read
How to Insert Line Break in SQL Server String?
In SQL Server there are various datatypes like int, float, char, nchar, etc but especially while we are dealing with text in VARCHAR and NVARCHAR columns, we might run into situations where we need to make the text look cleaner by adding line breaks. This could be for better organization, and readab
4 min read
How to Get the Insert ID in SQL?
When working with SQL databases, obtaining the insert ID (the auto-incremented primary key value) after inserting a new record is crucial for managing data relationships and ensuring seamless data referencing. In SQL databases, obtaining the insert ID after adding a new record to a table is a common
4 min read
How to Add Prefix in Auto Increment in MySQL?
In MySQL, you might need to create unique identifiers that combine a static prefix with an auto-incrementing number, such as order numbers or user IDs. This article provides a simple guide on how to set up a table and use a trigger to automatically generate these concatenated values. By following th
3 min read