QL AUTO INCREMENT field
Here is a clear, practical, and complete guide to the SQL AUTO INCREMENT field, including syntax for MySQL, PostgreSQL, SQL Server, and Oracle.
β What Is an AUTO INCREMENT Field?
An AUTO INCREMENT (or identity) field automatically generates sequential numeric values whenever a new row is inserted.
Used commonly for:
-
Primary keys
-
Surrogate IDs
-
Unique identifiers
Each database engine implements it differently.
π¦ MySQL β AUTO_INCREMENT
Insert without specifying id:
MySQL automatically generates:
-
1, 2, 3, β¦
Set starting value:
πͺ PostgreSQL β SERIAL / BIGSERIAL / GENERATED
Legacy (Common):
Types:
-
SERIALβ INT -
BIGSERIALβ BIGINT
Modern Standard (Recommended):
Equivalent to SQL standard.
π§ SQL Server β IDENTITY
Format:
Example:
π¨ Oracle β Identity Column (12c+)
Older versions used SEQUENCES + TRIGGERS.
π₯ Insert Behavior
AUTO INCREMENT fields fill automatically:
The DB generates the next ID.
π₯ Retrieve Last Inserted ID
MySQL:
PostgreSQL:
SQL Server:
Oracle:
π Reset AUTO INCREMENT
MySQL:
PostgreSQL:
SQL Server:
π§ Important Behavior Notes
β AUTO INCREMENT fields must be numeric
β They are often PRIMARY KEY, but not required
β Gaps in sequences are normal (due to deletes or rolled-back transactions)
β AUTO INCREMENT is not guaranteed gap-free
β Not suitable for sensitive identifiers (use UUID instead)
π§© REAL-WORLD EXAMPLE
User Table with Auto IDs (MySQL)
Orders Table with Identity (SQL Server)
Products Table with SERIAL (PostgreSQL)
π Best Practices
β Prefer system-managed surrogate keys (AUTO INCREMENT, SERIAL, IDENTITY)
β Use natural keys only when truly stable
β Donβt rely on sequence having no gaps
β For distributed systems β use UUID instead
β Always make AUTO INCREMENT the PRIMARY KEY
