Many times, we require updating the data based on the last updated table id.
We should write an update query in such a way that we can get the last updated ID in the update statement itself
The code mentioned below has been created in a generalized sense and can be used easily just by replacing the values in ”, which is demonstrated below:
CREATING A TABLE
CREATE TABLE
tbl(Rno INTEGER AUTO_INCREMENT ,
Name VARCHAR(50) ,
CONSTRAINT tbl_Rno PRIMARY KEY(Rno));
INSERT INTO tbl (Name) VALUES ('value1');
INSERT INTO tbl (Name) VALUES ('value2');
INSERT INTO tbl (Name) VALUES ('value3');
GETTING THE LAST UPDATED ID
The Logic over here suggests that we first update our last updated ID to 0 since it clears out any function previously performed then we update our values using the where clause/query in SQL and select the last updated ID using the @lastupdatedID query
SET @LastUpdateID := 0; UPDATE tbl SET Name = 'value_new',Rno = (SELECT @LastUpdateID := Rno) WHERE Name = 'value3'; SELECT @LastUpdateID AS LastUpdateID;
GETTING MULTIPLE LAST UPDATED ID
The Logic over here suggests that we update our values using the where clause/query in SQL and select the last updated ID using the @lastupdatedID query and to select multiple ID’s we use Concat query since it this code starts its searching from the bottom you would get our answer in a descending order as shown in the example.
SET @LastUpdateID = NULL;
UPDATE tbl SET Name = 'changed' WHERE Name 'changed'
AND (SELECT @LastUpdateID := CONCAT_WS(',', Rno, @LastUpdateID));
SELECT @LastUpdateID;
EXAMPLE #1 (For Last Updated ID)

Example #2 (For multiple Last Updated ID’s)

Recommended Posts:
- MySQL | Common MySQL Queries
- How to select the last row of a table using jQuery ?
- Last-child and last-of-type selector in SASS
- Expected number of coin flips to get two heads in a row?
- How to get the last n characters of a PHP string?
- Get the first and last item in an array using JavaScript
- How to get the last character of a string in JavaScript?
- How to get the first and last date of current month using JavaScript ?
- How to get value of a string after last slash in JavaScript?
- How to get the last item of JavaScript object ?
- How to get last day of a month from date in PHP ?
- How to Get First and Last Element of Slice in Golang?
- MySQL | LEAD() and LAG() Function
- PHP | MySQL UPDATE Query
- PHP | MySQL Database Introduction
- PHP | MySQL ( Creating Database )
- PHP | MySQL ( Creating Table )
- PHP | Inserting into MySQL database
- PHP | MySQL Select Query
- PHP | MySQL Delete Query
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : SohomPramanick

