MySQL — Auto Increment
Basic Auto Increment
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL
);
Inserting with Auto Increment
-- Let MySQL assign the ID
INSERT INTO users (name) VALUES ('Alice');
INSERT INTO users (name) VALUES ('Bob');
-- Explicitly set ID (not recommended)
INSERT INTO users (id, name) VALUES (100, 'Charlie');
Setting AUTO_INCREMENT Start
CREATE TABLE products (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100)
) AUTO_INCREMENT = 1000;
Altering AUTO_INCREMENT
ALTER TABLE users AUTO_INCREMENT = 5000;
Viewing Current Value
SHOW TABLE STATUS LIKE 'users';
Auto Increment Rules
| Rule | Detail |
|---|---|
| Column type | Must be INT, BIGINT, etc. |
| Key | Must be part of an index |
| One per table | Only one AUTO_INCREMENT column |
| Starts at 1 | By default |
| Gap-free | Gaps can occur with DELETE |
Resetting AUTO_INCREMENT
-- Reset to max + 1
ALTER TABLE users AUTO_INCREMENT = (
SELECT MAX(id) + 1 FROM users
);
Composite Keys
CREATE TABLE enrollments (
student_id INT,
course_id INT AUTO_INCREMENT,
PRIMARY KEY (student_id, course_id)
);
Mini Practice
Write SQL code that:
- Creates a table with AUTO_INCREMENT
- Inserts rows and observe auto-generated IDs
- Changes the AUTO_INCREMENT start value
- Shows the current AUTO_INCREMENT value
Up Next
Continue with Stored Procedures — reusable SQL code blocks.
Related Topics
Frequently Asked Questions about Auto Increment
What is Auto Increment in MySQL?
Auto Increment is a fundamental concept in MySQL. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Auto Increment?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Auto Increment.
Why is Auto Increment important in MySQL?
Auto Increment is essential for MySQL development. Understanding this concept will help you write better code and solve real-world problems more effectively.