← Back to MySQL Course | Chapter 4: Constraints | Lesson 8 of 8

AUTO_INCREMENT

Understanding AUTO_INCREMENT

AUTO_INCREMENT tells MySQL to generate the next integer in sequence automatically whenever a new row is inserted, which is why it's almost always paired with a primary-key ID column.

Example: Understanding AUTO_INCREMENT

sql
CREATE TABLE users (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50));

⚠️ This is MySQL-specific syntax. It cannot run in the browser editor. Practice this on your local MySQL installation.

Changing the Start Value

By default the sequence starts at 1 and increases by 1 each time, but you can set a custom starting value — useful when migrating data and needing new IDs to avoid colliding with an old system's existing range.

Example: Changing the Start Value

sql
CREATE TABLE users (id INT AUTO_INCREMENT PRIMARY KEY) AUTO_INCREMENT = 1000;

⚠️ This is MySQL-specific syntax. It cannot run in the browser editor. Practice this on your local MySQL installation.

Adding AUTO_INCREMENT to Existing Tables

You can add AUTO_INCREMENT to an existing column via ALTER TABLE, but that column must already be defined as a key (typically the primary key) — MySQL won't auto-generate values for an unindexed column.

Example: Adding AUTO_INCREMENT to Existing Tables

sql
ALTER TABLE users MODIFY id INT AUTO_INCREMENT;

⚠️ This is MySQL-specific syntax. It cannot run in the browser editor. Practice this on your local MySQL installation.

Removing AUTO_INCREMENT

Removing AUTO_INCREMENT stops the automatic number generation going forward, meaning future inserts must supply their own value for that column explicitly or rely on a DEFAULT instead.

Example: Removing AUTO_INCREMENT

sql
ALTER TABLE users MODIFY id INT;

⚠️ This is MySQL-specific syntax. It cannot run in the browser editor. Practice this on your local MySQL installation.

Retrieving the Last Inserted ID

LAST_INSERT_ID() returns the auto-generated ID from your most recent insert within the same session, which is exactly what you need when inserting a parent row and then immediately inserting related child rows referencing it.

Example: Retrieving the Last Inserted ID

sql
CREATE TABLE users (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50));
INSERT INTO users (name) VALUES ('Amit');
SELECT LAST_INSERT_ID();

⚠️ This is MySQL-specific syntax. It cannot run in the browser editor. Practice this on your local MySQL installation.

🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.