</>
Skip to content
MySQL lessons (40/48)

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

RuleDetail
Column typeMust be INT, BIGINT, etc.
KeyMust be part of an index
One per tableOnly one AUTO_INCREMENT column
Starts at 1By default
Gap-freeGaps 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:

  1. Creates a table with AUTO_INCREMENT
  2. Inserts rows and observe auto-generated IDs
  3. Changes the AUTO_INCREMENT start value
  4. 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.