Select nth highest value in MySQL


To select the nth highest value in MySQL, following is the syntax −

select distinct(yourColumnName) from yourTableName order by yourColumnName DESC limit (NthValue-1),1;

Let us first create a table −

mysql> create table DemoTable1594
   -> (
   -> Marks int
   -> );
Query OK, 0 rows affected (0.49 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1594 values(76);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable1594 values(95);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable1594 values(56);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1594 values(96);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable1594 values(89);
Query OK, 1 row affected (0.19 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1594;

This will produce the following output −

+-------+
| Marks |
+-------+
|    76 |
|    95 |
|    56 |
|    96 |
|    89 |
+-------+
5 rows in set (0.00 sec)

Here is the query to select nth highest value −

mysql> select distinct(Marks) from DemoTable1594 order by Marks DESC limit 2,1;

This will produce the following output −

+-------+
| Marks |
+-------+
|    89 |
+-------+
1 row in set (0.00 sec)

Updated on: 16-Dec-2019

167 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements