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)
- MySQL | Common MySQL Queries
- PHP | MySQL WHERE Clause
- MySQL | BIN() Function
- IFNULL in MySQL
- MongoDB vs MySQL
- MySQL | IF( ) Function
- MySQL | MD5 Function
- MySQL | DES_ENCRYPT ( ) Function
- MySQL | DES_DECRYPT ( ) Function
- MySQL | LEAD() and LAG() Function
- MySQL | OLD_PASSWORD Function
- PHP | MySQL ( Creating Database )
- MySQL | PASSWORD Function
- PHP | MySQL Database Introduction
- PHP | MySQL UPDATE 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 firstname.lastname@example.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