AUTO INCREMENT

AUTO INCREMENT Field

Auto-increment generates a unique number automatically when a new row is inserted. It is the usual way to create surrogate primary keys.

Syntax per Database

-- MySQL
CREATE TABLE Persons (ID INT NOT NULL AUTO_INCREMENT PRIMARY KEY, Name VARCHAR(100));

-- SQL Server (start at 1, step 1)
CREATE TABLE Persons (ID INT IDENTITY(1,1) PRIMARY KEY, Name VARCHAR(100));

-- PostgreSQL 10+ / Oracle 12c+ (standard)
CREATE TABLE Persons (ID INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY, Name VARCHAR(100));

-- PostgreSQL (older style)
CREATE TABLE Persons (ID SERIAL PRIMARY KEY, Name VARCHAR(100));

-- SQLite
CREATE TABLE Persons (ID INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT);

Try It

Example

Leave the ID out and the database fills it in:

CREATE TABLE Persons (ID INTEGER PRIMARY KEY AUTOINCREMENT, Name TEXT);
INSERT INTO Persons (Name) VALUES ('Kavya'), ('Arjun'), ('Neha');
SELECT * FROM Persons;

Result: 3 rows

IDName
1Kavya
2Arjun
3Neha

Things to Know

  • Gaps are normal: a rolled-back insert or a deleted row leaves a missing number. Never rely on ids being consecutive.
  • Get the generated id: LAST_INSERT_ID() (MySQL), SCOPE_IDENTITY() (SQL Server), RETURNING id (PostgreSQL), last_insert_rowid() (SQLite).
  • For ids created outside the database or merged across systems, consider UUIDs.