Find second max in a table using MySQL query?


You can use LIMIT 1 OFFSET 1. Let us first create a table −

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

Insert some records in the table using insert command −

mysql> insert into DemoTable values(1);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(2);
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable values(4);
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable values(204);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values(5);
Query OK, 1 row affected (0.76 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-------+
| Value |
+-------+
|     1 |
|     2 |
|     4 |
|   204 |
|     5 |
+-------+
5 rows in set (0.00 sec)

Here is the query to find second max value in a table −

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

This will produce the following output −

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

Updated on: 13-Dec-2019

387 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements