Get second largest marks from a MySQL table using subquery?

MySQLMySQLi Database

Let us first create a table −

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

Insert some records in the table using insert command −

mysql> insert into DemoTable values(78);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values(88);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values(67);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(76);
Query OK, 1 row affected (0.25 sec)
mysql> insert into DemoTable values(98);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(86);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values(89);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(99);
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-------+
| Marks |
+-------+
| 78    |
| 88    |
| 67    |
| 76    |
| 98    |
| 86    |
| 89    |
| 99    |
+-------+
8 rows in set (0.00 sec)

Following is the query to get a second-largest mark from MySQL table −

mysql> select Marks from DemoTable
where Marks=(select MAX(Marks) from DemoTable where Marks < (select MAX(Marks) from DemoTable));

This will produce the following output −

+-------+
| Marks |
+-------+
| 98    |
+-------+
1 row in set (0.03 sec)
raja
Published on 27-Sep-2019 07:37:04
Advertisements