Skip to content
Learn Netverks

Lesson

Step 8/36 22% through track

auto-increment-keys

AUTO_INCREMENT keys

Last reviewed May 28, 2026 Content v20260528
Track mode
sql_sandbox
Means
SQL sandbox
Reading
~1 min
Level
beginner

This lesson

This lesson teaches AUTO_INCREMENT keys: the SQL patterns, schema habits, and query reasoning you need before advancing in MySQL.

ID and upsert patterns differ from Postgres RETURNING—LAST_INSERT_ID and ON DUPLICATE KEY show up in PHP/Laravel codebases.

You will apply AUTO_INCREMENT keys in contexts like: Web apps on shared hosting, ecommerce, and many startups’ first production DB.

Copy MySQL SQL into the mysql client, local MySQL/MariaDB, or DB Fiddle (MySQL dialect)—use DESCRIBE and EXPLAIN where lessons show them. The in-browser lab ships later; mysql client is the practice path now.

When you can explain the previous lesson's ideas without copying example queries verbatim.

AUTO_INCREMENT generates integer primary keys on INSERT—pair with LAST_INSERT_ID() in the same session.

Define and use

CREATE TABLE items (
  id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(100) NOT NULL
);

INSERT INTO items (name) VALUES ('Cable');
SELECT LAST_INSERT_ID();

Practice: Run on database practice in mysql client.

Composite keys

Only one AUTO_INCREMENT column per table; it must be indexed (usually PRIMARY KEY).

UUID alternative

Apps may use CHAR(36) UUID strings to avoid predictable ids—trade-off: larger indexes.

Important interview questions and answers

  1. Q: LAST_INSERT_ID scope?
    A: Per connection session—safe in PHP PDO within same request.
  2. Q: Gap in sequence?
    A: Rollbacks and crashes can leave gaps—ids need not be contiguous.

Self-check

  1. How read id after INSERT?
  2. Are AUTO_INCREMENT values always consecutive?

Tip: Gaps in AUTO_INCREMENT sequence are normal after rollback.

Interview prep

LAST_INSERT_ID?

Per-connection id from latest AUTO_INCREMENT insert.

Gaps?

Normal after failed inserts or rollbacks.

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • Gaps OK?
  • UUID alternative?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump