Find Second Lowest Salary
We can use any of the below keywords to find the second lowest value from a table.
- MIN, which returns the minimum value of a column
- LIMIT, which returns a specific number of rows from a table
- TOP, which returns a specific number of top rows from a table
Let's assume a table with the below table definition and data, where we need to find the second-lowest salary.
ID Name Salary
===========================
1 Arun 20000
2 Kiran 15000
3 James 35000
4 Sammy 50000
5 Martin 25000
SQL Query Using MIN
SELECT MIN(salary) FROM employees WHERE salary > (SELECT MIN(salary) FROM employees);
In the above query, we have an inner query within the outer query, so the inner query executes first and is followed by the outer query as explained below.
- The inner query executes and returns the minimum salary from the table, which is 15000.
- Then, the outer query executes with the below WHERE condition, which returns the second minimum salary from the table, which is 20000.
- WHERE salary > 15000
SQL Query Using LIMIT
SELECT salary FROM (SELECT salary FROM employees ORDER BY salary ASC LIMIT 2) AS emp ORDER BY salary DESC LIMIT 1;
In the above query, we have an inner query within the outer query, so the inner query executes first and is followed by the outer query as explained below.
- The inner query sorts the table rows by salary in ascending order and returns the first 2 rows with salary amounts of 15000 and 20000 respectively.
- Then, the outer query sorts the inner query results by salary in descending order and returns the first 1 row with a salary amount of 20000, which is the second minimum salary.
SQL Query Using TOP
SELECT TOP 1 salary FROM FROM (SELECT TOP 2 salary FROM employees ORDER BY salary ASC) as emp ORDER BY salary DESC;
In the above query, we have an inner query within the outer query, so the inner query executes first and is followed by the outer query as explained below.
- The inner query sorts the table rows by salary in ascending order and returns the top 2 salary amounts 15000 and 20000 respectively.
- Then, the outer query sorts the inner query results by salary in descending order and returns the top 1 salary amount of 20000, which is the second minimum salary.
Overall
We now know the SQL Query to find the second minimum value from a specific table column.