MySQL / MariaDB How to get the id of the last inserted record in a table - LAST_INSERT_ID

  • Last update: Apr 3, 2024
  • Views: 42
  • Author: Admin
MySQL / MariaDB How to get the id of the last inserted record in a table - LAST_INSERT_ID

Colleagues hello to all.

In today's article, we'll talk about what LAST_INSERT_ID is and how to find it in a MySQL and MariaDB database.

LAST_INSERT_ID is the unique ID of the last record inserted in the database using the INSERT statement. To get this identifier, then in the table one field must be as the primary key. Because the primary key identifies a record in the database, it must be unique. To ensure that the record is always unique on insertion, we can assign the  AUTO_INCREMENT property to this field. The primary key field is usually called ID.

 

An example of a table with an ID field that has a primary key property and an AUTO_INCREMENT property.

last insert id


 

To get the ID of the last inserted record, we need to use the  LAST_INSERT_ID() built-in function. First you need to add a record to the table.

sql> INSERT INTO fio (first_name, last_name, middle_name) VALUES ('test_last_insert_id','test_last_insert_id','test_last_insert_id');

If anyone noticed, we do not specify the id field when adding data to the table, because the AUTO_INCREMENT property is enabled on this field, which means that the value of this field will automatically increase by one with each insertion.

Get the ID of the last record in the table.

sql> SELECT LAST_INSERT_ID();

last insert id

As a result, we got the ID of the last inserted record.


 

If we didn't add new data to the table and want to randomly get the ID of the last record, then we will get the number 0 as a result.

last insert id


 

Thank you all, I hope that my article helped you in some way.

SIMILAR ARTICLES