SQL Tutorial
The AUTO_INCREMENT
attribute in SQL is used to automatically generate a unique number whenever a new record is inserted into a table. This is often used with primary key column of the table.
MySQL:
In MySQL, you use the AUTO_INCREMENT
keyword to perform this task.
Here's an example of creating a table with an AUTO_INCREMENT
primary key:
CREATE TABLE Employees ( ID int NOT NULL AUTO_INCREMENT, FirstName varchar(255) NOT NULL, LastName varchar(255), PRIMARY KEY (ID) );
In this example, the ID
field is set to auto-increment. This means that every time you insert a new record into the Employees
table, you do not have to specify a value for the ID
field. MySQL will automatically add a unique value.
PostgreSQL:
In PostgreSQL, the SERIAL
keyword is used to perform auto-increment.
CREATE TABLE Employees ( ID SERIAL PRIMARY KEY, FirstName varchar(255) NOT NULL, LastName varchar(255) );
SQL Server:
In SQL Server, you use the IDENTITY
property to create an auto-increment field.
CREATE TABLE Employees ( ID int IDENTITY(1,1) PRIMARY KEY, FirstName varchar(255) NOT NULL, LastName varchar(255) );
In this SQL Server example, IDENTITY(1,1)
is used to create an auto-incrementing field. The two parameters specify the seed (starting value) and increment, respectively. So IDENTITY(1,1)
means start at 1 and increment by 1 for each new record.
Please note that in all these examples, you do not need to specify a value for the ID
field when inserting new records. The DBMS automatically assigns a new, unique value to the field.
Creating auto-increment columns in SQL: Define a column with AUTO_INCREMENT to automatically generate unique values.
CREATE TABLE TableName ( ID INT AUTO_INCREMENT, Name VARCHAR(255), PRIMARY KEY (ID) );
AUTO_INCREMENT in primary key definition: Use AUTO_INCREMENT when defining a primary key for automatic value generation.
CREATE TABLE TableName ( ID INT PRIMARY KEY AUTO_INCREMENT, Name VARCHAR(255) );
Setting starting value for AUTO_INCREMENT: Specify a starting value for the AUTO_INCREMENT sequence.
CREATE TABLE TableName ( ID INT AUTO_INCREMENT, Name VARCHAR(255), PRIMARY KEY (ID) ) AUTO_INCREMENT = 1001;
Restarting AUTO_INCREMENT sequence in SQL: Restart the AUTO_INCREMENT sequence to a specific value.
ALTER TABLE TableName AUTO_INCREMENT = 1;
Removing AUTO_INCREMENT property in SQL: Remove the AUTO_INCREMENT property from a column.
ALTER TABLE TableName MODIFY COLUMN ID INT;
Using AUTO_INCREMENT with composite keys: Incorporate AUTO_INCREMENT into a composite primary key.
CREATE TABLE TableName ( ID INT AUTO_INCREMENT, OtherID INT, Name VARCHAR(255), PRIMARY KEY (ID, OtherID) );
Retrieving last inserted ID with AUTO_INCREMENT: Retrieve the last inserted ID after an INSERT operation.
SELECT LAST_INSERT_ID();