Updating last entry of a particular ID in MySQL

MySQLMySQLi Database

To update the last entry of a particular ID in MySQL, use ORDER BY DESC LIMIT 1. This would allow you to update the last entry i.e. row records.

Let us first create a table −

mysql> create table DemoTable824(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   ClientName varchar(100),
   ClientAge int
);
Query OK, 0 rows affected (0.56 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable824(ClientName,ClientAge) values('Chris',23);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable824(ClientName,ClientAge) values('Robert',26);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable824(ClientName,ClientAge) values('Bob',24);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable824(ClientName,ClientAge) values('David',27);
Query OK, 1 row affected (0.18 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable824;

This will produce the following output −

+----+------------+-----------+
| Id | ClientName | ClientAge |
+----+------------+-----------+
|  1 | Chris      |        23 |
|  2 | Robert     |        26 |
|  3 | Bob        |        24 |
|  4 | David      |        27 |
+----+------------+-----------+
4 rows in set (0.00 sec)

Following is the query to update last entry of a particular ID in MySQL −

mysql> update DemoTable824 set ClientName='Adam',ClientAge=28 order by Id DESC limit 1;
Query OK, 1 row affected (0.20 sec)
Rows matched: 1 Changed: 1 Warnings: 0

Let us check the table records once again −

mysql> select *from DemoTable824;

This will produce the following output −

+----+------------+-----------+
| Id | ClientName | ClientAge |
+----+------------+-----------+
|  1 | Chris      |        23 |
|  2 | Robert     |        26 |
|  3 | Bob        |        24 |
|  4 | Adam       |        28 |
+----+------------+-----------+
4 rows in set (0.00 sec)
raja
Published on 03-Sep-2019 12:11:13
Advertisements