MySQL query to select bottom n records

MySQLMySQLi Database

Let us first create a table −

mysql> create table DemoTable724 (Value int);
Query OK, 0 rows affected (0.79 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable724 values(101);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable724 values(183);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable724 values(983);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable724 values(234);
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable724 values(755);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable724 values(435);
Query OK, 1 row affected (0.28 sec)
mysql> insert into DemoTable724 values(675);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable724 values(345);
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable724 values(948);
Query OK, 1 row affected (0.14 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable724;

This will produce the following output -

+-------+
| Value |
+-------+
| 101   |
| 183   |
| 983   |
| 234   |
| 755   |
| 435   |
| 675   |
| 345   |
| 948   |
+-------+
9 rows in set (0.00 sec)

Following is the query to select bottom n records. Here, we have selected 4 records after ordering in DESC. This would fetch us the last 4 records from the initial values −

mysql> select *from DemoTable724 order by Value DESC LIMIT 0,4;

This will produce the following output -

+-------+
| Value |
+-------+
| 983   |
| 948   |
| 755   |
| 675   |
+-------+
4 rows in set (0.00 sec)
raja
Published on 22-Aug-2019 10:59:07
Advertisements