Get a fixed number of results in descending order using a MySQL query

MySQLMySQLi Database

For descending order result, use DESC. However, LIMIT is used to get fixed number of records −

select *from yourTableName order by yourColumnName DESC LIMIT yourLimitNumber;

Let us first create a table −

mysql> create table DemoTable (Id int, Name varchar(100));
Query OK, 0 rows affected (0.73 sec)

Example

Insert some records in the table using insert command −

mysql> insert into DemoTable values(100,'John');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values(101,'Chris');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values(102,'Robert');
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable values(103,'Bob');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values(104,'Adam');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable values(105,'James');
Query OK, 1 row affected (0.18 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

+------+--------+
| Id   | Name   |
+------+--------+
| 100  | John   |
| 101  | Chris  |
| 102  | Robert |
| 103  | Bob    |
| 104  | Adam   |
| 105  | James  |
+------+--------+
6 rows in set (0.00 sec)

Get fixed number of records in descending order −

mysql> select *from DemoTable order by Name DESC LIMIT 3;

Output

+------+--------+
| Id   | Name   |
+------+--------+
| 102  | Robert |
| 100  | John   |
| 105  | James  |
+------+--------+
3 rows in set (0.00 sec)
raja
Published on 20-Aug-2019 11:19:50
Advertisements