Update only a single value from a MySQL table where select from same table ordered in descending order?


For this, use ORDER BY DESC with the LIMIT clause. The ORDER BY DESC order in descending order where LIMIT sets the number of records you want. Here, we will set LIMIT 1 since we want only a single record. Let us first create a table −

mysql> create table DemoTable
(
   StudentName varchar(100),
   StudentMarks int
);
Query OK, 0 rows affected (0.54 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('Chris',45);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values('Bob',78);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values('Mike',34);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('Robert',67);
Query OK, 1 row affected (0.16 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-------------+--------------+
| StudentName | StudentMarks |
+-------------+--------------+
| Chris       |           45 |
| Bob         |           78 |
| Mike        |           34 |
| Robert      |           67 |
+-------------+--------------+
4 rows in set (0.00 sec)

Following is the query to update only a single value from a MySQL table ordered in descending order −

mysql> update DemoTable
set StudentName='Adam'
order by StudentMarks DESC LIMIT 1;
Query OK, 1 row affected (0.10 sec)
Rows matched: 1 Changed: 1 Warnings: 0

Let us check the table records once again −

mysql> select *from DemoTable;

This will produce the following output −

+-------------+--------------+
| StudentName | StudentMarks |
+-------------+--------------+
| Chris       |           45 |
| Adam        |           78 |
| Mike        |           34 |
| Robert      |           67 |
+-------------+--------------+
4 rows in set (0.00 sec)

Updated on: 24-Sep-2019

50 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements