[MySQL] LAST_INSERT_ID()

LAST_INSERT_ID()



How did I encounter this?

While implementing 2 different tables in game DB, one for most of the game data and the other for release dates and platforms, I realized that from the first table, I need to get `game_id`. This means I need to send 3 queries: one to add the game, another to get the `game id`, and the other to add the date and platform with `game id`. The second query seems like a waste, but it is necessary. At least there is a way to make it simpler. LAST_INSERT_ID() is a statement to get the auto-increment value from the last inserted row 

Syntax

SELECT LAST_INSERT_ID() AS last_id;

Explanation

  • Insert a new row into the table.
  • Immediately follow it with SELECT LAST_INSERT_ID().
  • MySQL returns the auto-increment ID generated by the most recent INSERT.

Comments