SQL AUTO INCREMENT β Generate Unique Sequential IDs Automatically
Introduction β What is SQL AUTO INCREMENT?
The AUTO INCREMENT feature in SQL allows a column to automatically generate a unique number whenever a new row is inserted. Itβs commonly used for primary key columns to create IDs without manual input.
In this guide, youβll learn:
- How to define
AUTO INCREMENTacross SQL dialects - Default behavior, starting values, and reset options
- Differences between MySQL, PostgreSQL, and SQL Server
1. MySQL AUTO_INCREMENT Syntax
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100)
);
Automatically assigns a new id to each inserted row.
π 2. PostgreSQL β Use SERIAL or IDENTITY
-- Option 1: SERIAL
CREATE TABLE users (
id SERIAL PRIMARY KEY,
name VARCHAR(100)
);
-- Option 2: Standard SQL IDENTITY
CREATE TABLE users (
id INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name VARCHAR(100)
);
SERIAL is shorthand; IDENTITY is SQL-compliant.
3. SQL Server β IDENTITY Column
CREATE TABLE users (
id INT IDENTITY(1,1) PRIMARY KEY,
name VARCHAR(100)
);
Starts from 1, increments by 1 for each new row.
4. Reset or Restart AUTO INCREMENT
-- MySQL
ALTER TABLE users AUTO_INCREMENT = 1000;
-- PostgreSQL
ALTER SEQUENCE users_id_seq RESTART WITH 1000;
-- SQL Server
DBCC CHECKIDENT ('users', RESEED, 1000);
Useful when archiving or reseeding tables.
5. AUTO INCREMENT Notes
- One
AUTO INCREMENTcolumn per table (typicallyPRIMARY KEY) - Value is not reused if a row is deleted
- Cannot insert a manual value unless explicitly allowed
- Some engines allow gaps (e.g., rollback after failure)
Best Practices
| Recommended | Avoid This |
|---|---|
Use for numeric PRIMARY KEY IDs | Using for business-specific identifiers |
| Allow DB to manage keys automatically | Relying on app logic to increment manually |
| Reset only when needed | Frequent reseeding in live databases |
Summary β Recap & Next Steps
AUTO INCREMENT is a powerful feature to automatically generate unique keys. It simplifies row insertion and ensures consistent primary key assignment.
Key Takeaways:
- Use
AUTO_INCREMENT,SERIAL, orIDENTITYdepending on DBMS - Automatically assigns sequential values
- Reset carefully using ALTER/RESEED commands
Real-World Relevance:
Used in customer IDs, order numbers, ticketing systems, and logs.
FAQ β SQL AUTO INCREMENT
Can I have more than one AUTO INCREMENT column?
No. Most DBMS allow only one per table.
What happens if I insert a value manually?
Depends on DBMS settings. Some allow overrides, others raise errors.
Does AUTO INCREMENT fill gaps after deletions?
No. It continues from the last highest value.
Is AUTO INCREMENT zero-based?
No. Most systems start at 1 by default.
Share Now :
