Lesson

MySQL AUTO_INCREMENT

10 min reading
Free Course

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_INCREMENT Sequences: Rolled-back transactions, failed INSERT constraints, and INSERT ... ON DUPLICATE KEY UPDATE still consume counter increments. Never assume id sequences are gap-free—use a separate invoice number generator if auditors require unbroken sequences.
  • Use BIGINT UNSIGNED for High-Volume Tables: A signed INT overflows at 2,147,483,647. Event logs, orders, and webhooks can exhaust signed INT rapidly if gaps occur, whereas BIGINT UNSIGNED reaches 18.4 quintillion.
  • Never Compute Next ID with MAX(id) + 1: MAX(id) + 1 causes race conditions and duplicate key crashes under concurrent requests; let AUTO_INCREMENT manage 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.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
MySQL Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum