Skip to content

SQL AUTO INCREMENT Field

An auto-increment column fills itself in. Each new row gets the next number, so an insert does not need to supply one. It is the usual way to give a table a primary key with no meaning of its own.

Take a supplier table whose SupplierID numbers itself. With suppliers 1 to 3 already on the list, an insert that leaves the ID out:

INSERT INTO Suppliers (Name, Service, City)
VALUES ('Fairlie Sound', 'Sound', 'Glasgow');

gets the next number:

SupplierID Name
4 Fairlie Sound

The SQL standard, followed by PostgreSQL 10 and later, Oracle 12c and later and Db2, uses an identity column:

CREATE TABLE Suppliers (
SupplierID int GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
Name varchar(100) NOT NULL,
Service varchar(50),
City varchar(50)
);

The others have their own wording for the same column:

Database Column definition
MySQL SupplierID int AUTO_INCREMENT PRIMARY KEY
SQL Server SupplierID int IDENTITY(1, 1) PRIMARY KEY
SQLite SupplierID INTEGER PRIMARY KEY
Access SupplierID AUTOINCREMENT PRIMARY KEY
PostgreSQL, older versions SupplierID serial PRIMARY KEY

SQL Server’s IDENTITY(1, 1) means start at 1 and go up by 1; IDENTITY(1000, 10) would start at 1000 and go up in tens.

To start numbering at 100, for instance so supplier numbers are always three digits:

Database Statement
MySQL ALTER TABLE Suppliers AUTO_INCREMENT = 100;
PostgreSQL ALTER TABLE Suppliers ALTER COLUMN SupplierID RESTART WITH 100;
SQL Server set it when creating the column, with IDENTITY(100, 1)

Auto-increment numbers are unique, but not guaranteed to be consecutive. A deleted row leaves its number unused, and an insert that fails or is rolled back can use up a number too. Treat the ID as a label, never as a count of rows or a sequence that must be unbroken. Where a business needs unbroken numbering, such as some invoice series, generate those numbers separately.