π’ 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 :
