How to get the generated key from a MySQL auto_increment field after an INSERT

Here's a quick look at how to get the generated key from a MySQL database table after performing a SQL INSERT statement on a table that has an auto_increment field. (Some databases also refer to this as an identity field.)

To get the generated key from a MySQL database table, just use the MySQL LAST_INSERT_ID function, calling it as shown below, immediately after performing your INSERT command (and very importantly, also using the same connection):

SELECT LAST_INSERT_ID();

Here's a blurb from this MySQL page:

... LAST_INSERT_ID() (with no argument) returns the first automatically generated value that was set for an AUTO_INCREMENT column by the most recently executed INSERT statement to affect such a column.

I'm a little short on time today, so please read the page I linked to for more information.

Also, remember that if you're using a framework like Spring, it will probably have convenience functions that you can use to get the generated key from an auto_increment field.