Logic
- Get salary in decreasing order and give limit n. So, the last salary is required
- Now arrange this is increasing order (ascending order)
- Take the first record by using Limit 1, to get the answer
mysql> select * from emp;
+--------+
| salary |
+--------+
| 20000 |
| 50000 |
| 35000 |
| 60000 |
+--------+
Ques - Find 3rd max salary
mysql> select salary from emp
order by salary desc limit 3;
+--------+
| salary |
+--------+
| 60000 |
| 50000 |
| 35000 |
+--------+
3 rows in set (0.00 sec)
mysql> select salary from (select salary from emp order by salary desc limit 3) a order by salary
-> ;
+--------+
| salary |
+--------+
| 35000 |
| 50000 |
| 60000 |
+--------+
3 rows in set (0.00 sec)
mysql> select salary from (select salary from emp order by salary desc limit 3) a order by salary
limit 1;
+--------+
| salary |
+--------+
| 35000 |
+--------+
1 row in set (0.00 sec)
--------------------------------------------------------------------------------------------------------------------------
Ques - find 2nd min salary = 35000
mysql> select * from emp order by salary limit 2;
asc - first min sal , second min sal
+--------+
| salary |
+--------+
| 20000 |
| 35000 |
+--------+
2 rows in set (0.00 sec)
mysql> select salary from (select salary from emp order by salary limit 2)a order by salary desc ;
+--------+
| salary |
+--------+
| 35000 |
| 20000 |
+--------+
2 rows in set (0.00 sec)
mysql> select salary from (select salary from emp order by salary limit 2)a order by salary desc limit 1 ;
+--------+
| salary |
+--------+
| 35000 |
+--------+
1 row in set (0.00 sec)