Can we update a row with the highest ID in a single MySQL query?


Yes, we can do that. Let us first create a table −

mysql> create table DemoTable
   (
   ID int,
   GameScore int
   );
Query OK, 0 rows affected (0.55 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(15,848747);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values(13,909049);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(34,98474646);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values(31,948474);
Query OK, 1 row affected (0.27 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

+------+-----------+
| ID   | GameScore |
+------+-----------+
| 15   | 848747    |
| 13   | 909049    |
| 34   | 98474646  |
| 31   | 948474    |
+------+-----------+
4 rows in set (0.00 sec)

Following is the query to update a row with the highest ID in a single query −

mysql> update DemoTable set GameScore=GameScore+10 ORDER BY ID DESC LIMIT 1;
Query OK, 1 row affected (0.19 sec)
Rows matched : 1 Changed : 1 Warnings : 0

Let us check the table record once again −

mysql> select *from DemoTable;

Output

+------+-----------+
| ID   | GameScore |
+------+-----------+
| 15   | 848747    |
| 13   | 909049    |
| 34   | 98474656  |
| 31   | 948474    |
+------+-----------+
4 rows in set (0.00 sec)
raja
Published on 13-Jun-2019 12:08:09
Advertisements