MySQL query to perform delete operation where id is the biggest?

MySQLMySQLi Database

You can use ORDER BY DESC command with LIMIT 1 for this since we need to delete only a single ID.

Let us first create a table −

mysql> create table DemoTable
(
   UserId int,
   UserName varchar(20)
);
Query OK, 0 rows affected (0.57 sec)

Insert records in the table using insert command −

mysql> insert into DemoTable values(100,'John');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values(234,'Mike');
Query OK, 1 row affected (0.28 sec)
mysql> insert into DemoTable values(145,'Sam');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values(278,'Carol');
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable values(289,'David');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(277,'Bob');
Query OK, 1 row affected (0.14 sec)

Display records from the table using select command −

mysql> select *from DemoTable;

This will produce the following output −

+--------+----------+
| UserId | UserName |
+--------+----------+
| 100    | John     |
| 234    | Mike     |
| 145    | Sam      |
| 278    | Carol    |
| 289    | David    |
| 277    | Bob      |
+--------+----------+
6 rows in set (0.00 sec)

Following is the query to perform delete where id is the biggest −

mysql> delete from DemoTable order by UserId DESC limit 1;
Query OK, 1 row affected (0.15 sec)

Let us display all records from the table in order to check the biggest id has been deleted or not. Here, id 289 deleted successfully −

mysql> select *from DemoTable;

This will produce the following output −

+--------+----------+
| UserId | UserName |
+--------+----------+
| 100    | John     |
| 234    | Mike     |
| 145    | Sam      |
| 278    | Carol    |
| 277    | Bob      |
+--------+----------+
5 rows in set (0.00 sec)
raja
Published on 29-Apr-2019 15:28:05
Advertisements