How to select the top two values using LIMIT in MySQL?

MySQLMySQLi Database

Since you need the top values, use ORDER BY DESC. With that, for two values, use LIMIT 2. For our example, let us first create a table −

mysql> create table DemoTable
(
   Amount int
);
Query OK, 0 rows affected (0.73 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(986);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values(1010);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable values(769);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values(989);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values(999);
Query OK, 1 row affected (0.15 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+--------+
| Amount |
+--------+
|    986 |
|   1010 |
|    769 |
|    989 |
|    999 |
+--------+
5 rows in set (0.00 sec)

Following is the query to select the top two values using LIMIT in MySQL −

mysql> select *from DemoTable order by Amount DESC LIMIT 2;

This will produce the following output −

+--------+
| Amount |
+--------+
|   1010 |
|    999 |
+--------+
2 rows in set (0.00 sec)
raja
Published on 26-Sep-2019 08:34:52
Advertisements