What is the use of MySQL LAST_INSERT_ID() function?

MySQLMySQLi Database

MySQL LAST_INSERT_ID() function is used to obtain the most recent generated sequence number by AUTO_INCREMENT.

Example

In this example, we are creating a table named ‘Student’ having an AUTO_INCREMENT column. We insert two values in the column ‘Name’ and when we use INSERT_LAST_ID() function then it returns the most recent generated sequence number i.e. 2.

mysql> Create table Student(Id INT PRIMARY KEY NOT NULL AUTO_INCREMENT, Name Varchar(5));
Query OK, 0 rows affected (0.13 sec)

mysql> Insert into student(Name) Values('Raman');
Query OK, 1 row affected (0.06 sec)

mysql> Insert into student(Name) Values('Rahul');
Query OK, 1 row affected (0.07 sec)

mysql> Select* from student;
+----+-------+
| Id | Name |
+----+-------+
| 1 | Raman |
| 2 | Rahul |
+---+-------+
2 rows in set (0.00 sec)

mysql> Select Last_insert_id();
+------------------+
| Last_insert_id() |
+------------------+
|                2 |
+------------------+
1 row in set (0.00 sec)
raja
Published on 19-Feb-2018 17:34:34
Advertisements