MySQL query to get first two highest column values from a table?



To get the first two highest columns, use ORDER BY. With that, use LIMIT 2 to get only the first 2 −

select *from yourTableName order by yourColumnName DESC LIMIT 2;

Let us first create a table −

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

Insert some records in the table using insert command −

mysql> insert into DemoTable values(90); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable values(70); Query OK, 1 row affected (0.28 sec) mysql> insert into DemoTable values(40); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values(120); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values(98); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values(105); Query OK, 1 row affected (0.19 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

+-------+ | Value | +-------+ |    90 | |    70 | |    40 | |   120 | |    98 | |   105 | +-------+ 6 rows in set (0.00 sec)

Following is the query to get first two highest column values from a table −

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

Output

+-------+ | Value | +-------+ |   120 | |   105 | +-------+ 2 rows in set (0.00 sec)
Updated on: 2019-07-30T22:30:26+05:30

507 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements