Summary: in this tutorial, you will learn how to use the MySQL LAST_INSERT_ID function to obtain the generated sequence number of the last insert record.
In database design, we often use a surrogate key to generate unique values for the identity column by setting the AUTO_INCREMENT attribute for the column. When we insert a new record into the table that has AUTO_INCREMENT column, MySQL generates a unique ID automatically based on the column’s definition.
For more information on how to set AUTO_INCREMENT attribute for a column, check it out the MySQL sequence tutorial.
We can obtain the generated sequence number by using the MySQL LAST_INSERT_ID function and use the number for the next statements e.g., inserting a new row into the related tables.
Let’s take a look at an example of using MySQL LAST_INSERT_ID function: