Select Three Highest Values and Sort Alphabetically in MySQL



For this, you can use the ORDER BY clause. Let us first create a table −

mysql> create table DemoTable
(
   Name varchar(40),
   Score int
);
Query OK, 0 rows affected (1.11 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('Chris',45);
Query OK, 1 row affected (0.26 sec)
mysql> insert into DemoTable values('Bob',98);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values('David',78);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values('Mike',96);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('Carol',43);
Query OK, 1 row affected (0.20 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-------+-------+
| Name  | Score |
+-------+-------+
| Chris |    45 |
| Bob   |    98 |
| David |    78 |
| Mike  |    96 |
| Carol |    43 |
+-------+-------+
5 rows in set (0.00 sec)

Following is the query to select three highest values from “Score” column and sort the corresponding “Name” column alphabetically −

mysql> select *from (select Name,Score from DemoTable order by Score desc,Name asc limit 3) tbl
order by Name;

This will produce the following output −

+-------+-------+
| Name  | Score |
+-------+-------+
| Bob   |    98 |
| David |    78 |
| Mike  |    96 |
+-------+-------+
3 rows in set (0.03 sec)
Updated on: 2019-10-01T08:02:35+05:30

797 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements