LAST_INSERT_ID([expression])

Description: Returns the last value generated automatically in an AUTO_INCREMENT column as the result of an INSERT.

Returns the last value generated by the same thread, not a value generated by another thread. Returns 0 if no value has been generated.

Note that if an insert created several new rows, LAST_INSERT_ID() returns the value from the first row inserted (not the last).

Examples:

  • LAST_INSERT_ID() returns 1000023.

LAST_INSERT_ID() can be used with an optional expression: this version is intended for use with an UPDATE statement, which can produce sequences without the need for storing the ID in an application.

Example:

UPDATE some_table
  SET some_id=LAST_INSERT_ID(some_id+1)
					

Get Sams Teach Yourself MySQL in 21 Days, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.