✏️ Explanatory Question
Level: Basic — Tests your understanding of how MySQL generates unique IDs automatically.
AUTO_INCREMENT is a column attribute that automatically generates a unique, sequential number for each new row inserted. It is most commonly used on a Primary Key column so you don't have to manually assign IDs.
By default, the sequence starts at 1 and increases by 1 for every new record. When you insert a row, you can leave the AUTO_INCREMENT column out (or pass NULL/DEFAULT) and MySQL fills in the next value automatically.
AUTO_INCREMENT = n.auto_increment_increment system variable.TRUNCATE resets the counter; DELETE does not.LAST_INSERT_ID() to fetch the most recently generated value.-- Define an AUTO_INCREMENT primary key
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50)
) AUTO_INCREMENT = 100; -- start counting from 100
-- Omit id: MySQL assigns it automatically
INSERT INTO users (name) VALUES ('Rumman'); -- id = 100
INSERT INTO users (name) VALUES ('Ansari'); -- id = 101
-- Get the last generated ID
SELECT LAST_INSERT_ID(); -- returns 101
-- Reset the counter (only works if table is empty / higher than max)
ALTER TABLE users AUTO_INCREMENT = 500;