Friday, January 11, 2013

Retrieve second lowest value from a table


Question: How can I retrieve the second lowest salary amount from a salary table?
Answer: To retrieve the second lowest salary from a salary table, you could run the following query: (please note that the subquery is sorted in ascending order)
SELECT salary_amount
FROM (select salary2.*, rownum rnum from
            (select * from salary ORDER BY salary_amount) salary2
      where rownum <= 2 )
WHERE rnum >= 2;
If you wanted to retrieve all fields from the salary table for the second lowest salary, you could run the following query: (please note that the subquery is sorted in ascending order)
SELECT *
FROM (select salary2.*, rownum rnum from
             (select * from salary ORDER BY salary_amount) salary2
      where rownum <= 2 )
WHERE rnum >= 2;