Lesson

MySQL LAST_INSERT_ID() Function

10 min reading
Free Course

MySQL LAST_INSERT_ID() Function

The MySQL LAST_INSERT_ID() function returns the first automatically generated AUTO_INCREMENT value created by the most recent INSERT statement in the current database connection. Because it is scoped strictly per connection, concurrent users inserting rows simultaneously will never overwrite each other's IDs.

Syntax

LAST_INSERT_ID()
-- Optional sequence-generator form:
LAST_INSERT_ID(expr)
  • No arguments: Returns the last AUTO_INCREMENT BIGINT UNSIGNED value generated in this session, or 0 if no AUTO_INCREMENT insert has occurred yet.
  • expr: Optional expression that sets the session's stored value to expr and returns expr.

Practical Example

After inserting a new parent record into demo_orders, call LAST_INSERT_ID() to attach child items using the newly generated order_id.

INSERT INTO demo_orders (customer_id, status, total_amount)
VALUES (104, 'pending', 199.00);

SELECT LAST_INSERT_ID() AS created_order_id;
created_order_id
1005

Common Mistakes & NULL Behavior

  • NULL behavior: Calling LAST_INSERT_ID() with zero arguments never returns NULL; before any auto-increment insert in the session, it returns 0. If you pass LAST_INSERT_ID(NULL), it resets the stored value to 0 and returns 0.
  • Multi-row INSERT trap: If a single statement inserts 3 rows (VALUES (...), (...), (...)) generating IDs 10, 11, 12, LAST_INSERT_ID() returns 10 (the first generated ID, not 12).
  • Explicit ID inserts do not update it: Inserting a manual primary key value (INSERT INTO demo_orders (order_id, ...) VALUES (999, ...)) without triggering AUTO_INCREMENT leaves LAST_INSERT_ID() unchanged!
  • Failed or ignored inserts: INSERT IGNORE that skips a duplicate row does not update LAST_INSERT_ID().

Frequently Asked Questions

Is LAST_INSERT_ID() safe when multiple users insert at once?

Yes. MySQL tracks LAST_INSERT_ID() separately for every client connection, so another session's INSERT cannot affect your return value.

What does LAST_INSERT_ID() return after a bulk INSERT of 5 rows?

It returns the AUTO_INCREMENT ID of the first row inserted by that statement, allowing you to compute sequential IDs (id to id + 4 when auto_increment_increment = 1).

Why did LAST_INSERT_ID() return 0 after my INSERT?

Either the table has no AUTO_INCREMENT column, your INSERT supplied an explicit primary key value, or the statement failed/ignored all rows.

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