MySQL AUTO_INCREMENT
MySQL AUTO_INCREMENT: Automatic Sequential Primary Keys
The MySQL AUTO_INCREMENT attribute automatically generates a unique, incrementing integer whenever a new row is inserted without an explicit key value. Almost every entity table uses an AUTO_INCREMENT primary key because sequential integers keep InnoDB B-tree inserts fast and compact.
Basic Syntax
Apply AUTO_INCREMENT to an indexed integer primary key column:
CREATE TABLE demo_products (
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
product_name VARCHAR(100) NOT NULL
) AUTO_INCREMENT = 1000;
Setting AUTO_INCREMENT = 1000 starts generated IDs at 1000 (useful for public order numbers), while omitting it starts at 1.
Practical SQL Example
After inserting a row into demo_customers, read back the generated ID safely on the same connection using LAST_INSERT_ID():
INSERT INTO demo_customers (first_name, last_name, email)
VALUES ('Elena', 'Brooks', 'elena@example.com');
-- Connection-safe: returns the ID generated by THIS session only
SELECT LAST_INSERT_ID() AS new_customer_id;
Common Mistakes and Best Practices
- Expect Gaps in
AUTO_INCREMENTSequences: Rolled-back transactions, failedINSERTconstraints, andINSERT ... ON DUPLICATE KEY UPDATEstill consume counter increments. Never assumeidsequences are gap-free—use a separate invoice number generator if auditors require unbroken sequences. - Use
BIGINT UNSIGNEDfor High-Volume Tables: A signedINToverflows at2,147,483,647. Event logs, orders, and webhooks can exhaust signedINTrapidly if gaps occur, whereasBIGINT UNSIGNEDreaches18.4 quintillion. - Never Compute Next ID with
MAX(id) + 1:MAX(id) + 1causes race conditions and duplicate key crashes under concurrent requests; letAUTO_INCREMENTmanage locking atomically.
Frequently Asked Questions
Is LAST_INSERT_ID() safe when multiple users insert at the same time?
Yes, LAST_INSERT_ID() is scoped per client connection, so concurrent inserts from other sessions never overwrite your session's value.
What happens if I insert NULL or 0 into an AUTO_INCREMENT column?
MySQL generates the next sequential ID automatically (unless NO_AUTO_VALUE_ON_ZERO SQL mode is active for 0).
Does AUTO_INCREMENT reset after a server restart in MySQL 8?
No, MySQL 8 persists the current maximum counter in the redo log, fixing the older MySQL 5.7 behavior where deleted max IDs could be reused after a restart.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.