MySQL LAST_INSERT_ID() Function
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_INCREMENTBIGINT UNSIGNEDvalue generated in this session, or0if noAUTO_INCREMENTinsert has occurred yet. expr: Optional expression that sets the session's stored value toexprand returnsexpr.
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 returnsNULL; before any auto-increment insert in the session, it returns0. If you passLAST_INSERT_ID(NULL), it resets the stored value to0and returns0. - Multi-row
INSERTtrap: If a single statement inserts 3 rows (VALUES (...), (...), (...)) generating IDs10, 11, 12,LAST_INSERT_ID()returns10(the first generated ID, not12). - Explicit ID inserts do not update it: Inserting a manual primary key value (
INSERT INTO demo_orders (order_id, ...) VALUES (999, ...)) without triggeringAUTO_INCREMENTleavesLAST_INSERT_ID()unchanged! - Failed or ignored inserts:
INSERT IGNOREthat skips a duplicate row does not updateLAST_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.
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.