LAST_INSERT_ID() function in MySQL is used to find the last row’s AUTO_INCREMENT id which is being included or revised in a table.
Features :
- This function is used to find the last row’s AUTO_INCREMENT id.
- This function comes under Advanced Functions.
- This function accepts only one parameter namely expression.
Syntax :
LAST_INSERT_ID(expression)
Parameter :
This method accepts only one parameter is given below:
- Expression: Specified expression which may be optional.
Returns :
It returns the last row’s AUTO_INCREMENT id of the stated table.
Now we see some examples of the LAST_INSERT_ID() Function in MySQL.
Example 1 :
Using LAST_INSERT_ID() function and getting the output.
Query:
SELECT LAST_INSERT_ID();
Output :
Here, notable is specified so the last insert id is zero.
Example 2 :
Using LAST_INSERT_ID() function and finding the last insert id of the table of float values.
Query:
CREATE TABLE floats13 ( user_id int NOT NULL AUTO_INCREMENT, float_val float, PRIMARY KEY(user_id) ); INSERT floats13(float_val) VALUES (1.2); INSERT floats13(float_val) VALUES (2.1); INSERT floats13(float_val) VALUES (6.3); INSERT floats13(float_val) VALUES (9.0); INSERT floats13(float_val) VALUES (7.0); SELECT LAST_INSERT_ID();
Output :
Example 3 :
Using LAST_INSERT_ID() function and getting the last insert id for a table of 3 columns.
Query:
CREATE TABLE package33 ( user_id int NOT NULL AUTO_INCREMENT, item VARCHAR(10), mrp int, PRIMARY KEY(user_id) ); INSERT package33(item, mrp) VALUES ('book1', 250); INSERT package33(item, mrp) VALUES ('book2', 500); INSERT package33(item, mrp) VALUES ('book3', 750); SELECT LAST_INSERT_ID();
Output :
Example 4 :
Using LAST_INSERT_ID() function and getting the last insert id of all the 3 variables.
Query:
CREATE TABLE package15 ( user_id int NOT NULL AUTO_INCREMENT, item VARCHAR(10), mrp int, sp int, PRIMARY KEY(user_id) ); INSERT package15(item, mrp, sp) VALUES ('book1', 250, 240); INSERT package15(item, mrp, sp) VALUES ('book2', 350, 320); INSERT package15(item, mrp, sp) VALUES ('book3', 400, 350); SELECT LAST_INSERT_ID() FROM package15;
Output :
This function is used to find the last row’s AUTO_INCREMENT id.