MySQL ON DUPLICATE KEY - last insert id?
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.
MySQL's ON DUPLICATE KEY UPDATE
is a valuable feature that allows you to handle situations where you need to either insert new records or update existing ones based on unique key constraints. This feature provides an efficient mechanism for maintaining data integrity and helps reduce the complexity of managing insert and update operations separately.
When using ON DUPLICATE KEY UPDATE
, the operation will:
- Insert a new row if no duplicate key exists.
- Update the existing row if a duplicate key is detected.
A commonly asked question is how this affects obtaining the LAST_INSERT_ID()
, particularly when combined with the operation of updating existing rows.
Understanding LAST_INSERT_ID()
In MySQL, the function LAST_INSERT_ID()
is used to retrieve the last automatically generated AUTO_INCREMENT
value inserted into a table. This function plays a significant role in applications that need to keep track of newly inserted row identifiers, especially when these rows are involved in creating related entities.
How ON DUPLICATE KEY UPDATE
Handles LAST_INSERT_ID()
When you use ON DUPLICATE KEY UPDATE
, the behavior of LAST_INSERT_ID()
can vary:
- Inserting a New Row:
- If a new row is inserted because no duplicate key exists,
LAST_INSERT_ID()will hold the ID of the inserted row.
- Updating an Existing Row:
- If an existing row is updated due to a duplicate key conflict,
LAST_INSERT_ID()remains unchanged from the most recent successfulAUTO_INCREMENTinsertion. However, you can manipulate it using theVALUES()function within theON DUPLICATE KEY UPDATEclause.
Example: Inserting with ON DUPLICATE KEY UPDATE
Consider a table users
as follows:
- New Insertion: If
username = 'john_doe'doesn't exist, a new row is inserted. - Duplicate Key Update: If
username = 'john_doe'already exists, theemailfield is updated, andid = LAST_INSERT_ID(id)ensures thatLAST_INSERT_ID()returns the ID of the affected row. - Efficiency: Condenses
INSERTandUPDATEfunctionality into a single operation. - Atomic Operations: Helps ensure atomicity and integrity, particularly for concurrent operations.
- Performance: Reduces the overhead of separate commands when dealing with isolated insert/update challenges.
- Triggers: Be mindful of how triggers might interact with
ON DUPLICATE KEY UPDATE. Ensure triggers do not inadvertently alter logic, which could affectLAST_INSERT_ID(). - Horizontal Scaling: Consider potential pitfalls in distributed systems where ID tracking might differ across nodes.
- Error Handling: Implement appropriate error handling to manage cases where neither an insertion nor an update should occur, such as complex integrity constraints.
Related reading
- MySQL ON DUPLICATE KEY UPDATE for multiple rows insert in single query
- MySQL OPTIMIZE all tables?
- MySQL OR vs IN performance
- MySQL 'Order By' - sorting alphanumeric correctly
- MySQL order by before group by
- MySql order by specific ID values
- MySQL Orderby a number, Nulls last
- MySQL pagination without double-querying?

System Design Fundamentals
Build a strong foundation in designing scalable, reliable distributed systems.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.