Tutorialspoint

Select the topmost record from a table ordered by desc on the basis of ID?


1 Answer
Kumar Varma

For this, use ORDER BY DESC with LIMIT 1. Let us first create table −

mysql> create table DemoTable
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> UserName varchar(100),
   -> UserMessage text
   -> );
Query OK, 0 rows affected (1.17 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(UserName,UserMessage) values('Adam','Hi');
Query OK, 1 row affected (0.92 sec)

mysql> insert into DemoTable(UserName,UserMessage) values('Chris','Awesome');
Query OK, 1 row affected (0.52 sec)

mysql> insert into DemoTable(UserName,UserMessage) values('Robert','Nice');
Query OK, 1 row affected (0.65 sec)

mysql> insert into DemoTable(UserName,UserMessage) values('David','Good Morning!!!');
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----+----------+-----------------+
| Id | UserName | UserMessage     |
+----+----------+-----------------+
|  1 | Adam     | Hi     |
|  2 | Chris    | Awesome     |
|  3 | Robert   | Nice     |
|  4 | David    | Good Morning!!! |
+----+----------+-----------------+
4 rows in set (0.00 sec)

Following is the query to select the topmost record from a table −

mysql> select *from DemoTable order by Id DESC limit 1;

This will produce the following output −

+----+----------+-----------------+
| Id | UserName | UserMessage     |
+----+----------+-----------------+
|  4 | David    | Good Morning!!! |
+----+----------+-----------------+
1 row in set (0.00 sec)

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.