MySQL query to select the nth highest value in a column by skipping values


To get the nth highest value in a column, you can use LIMIT OFFSET. Here, OFFSET is used to skip the values. Let us first create a table −

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

Insert some records in the table using insert command −

mysql> insert into DemoTable values(100);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values(140);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values(90);
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable values(80);
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable values(89);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values(98);
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable values(58);
Query OK, 1 row affected (0.10 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-------+
| Value |
+-------+
|   100 |
|   140 |
|    90 |
|    80 |
|    89 |
|    98 |
|    58 |
+-------+
7 rows in set (0.00 sec)

Following is the query to get the nth highest value in a column. Here, we are skipping 3 values using OFFSET 3. The same gives us the 4th highest value after using ORDER BY −

mysql> select Value from DemoTable
   order by Value limit 1 offset 3;

This will produce the following output −

+-------+
| Value |
+-------+
|    90 |
+-------+
1 row in set (0.00 sec)

Updated on: 04-Oct-2019

127 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements