Second Highest Salary










1















Write a SQL query to get the second highest salary from the Employee table.



 | Id | Salary |
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |


For example, given the above Employee table, the query should return 200 as the second highest salary. If there is no second highest salary, then the query should return null.



 | SecondHighestSalary |
| 200 |


This is a question from Leetcode, for which I entered the following code:



 SELECT CASE WHEN Salary = '' 
THEN NULL
ELSE Salary
END AS SecondHighestSalary
FROM (SELECT TOP 2 Salary
,ROW_NUMBER() OVER (ORDER BY Salary DESC) AS Num
FROM Employee
ORDER BY Salary DESC) AS T
WHERE T.Num = 2


It says that the query does not return NULL if there's no value for second highest salary.
For eg. if the table is



 | Id | Salary| 
| 1 | 100 |


The query should return



 |SecondHighestSalary|
| null |


and not



 |SecondHighestSalary|
| |









share|improve this question
























  • geeksforgeeks.org/sql-query-to-find-second-largest-salary

    – Prasad Telkikar
    Nov 14 '18 at 9:54











  • "Second highest" is ambiguous. What do you want to do in case of a tie? E.g. add another record with salary 300 to your sample table. Then: do you want to show 300 or 200? You must answer this question first, before you can write the query.

    – Thorsten Kettner
    Nov 14 '18 at 10:11












  • @ThorstenKettner even in case of tie, it should display the next highest value, no matter how many times the first highest value is repeated. If no second highest value is present, then it should return NULL.

    – SukuAD
    Nov 14 '18 at 12:30















1















Write a SQL query to get the second highest salary from the Employee table.



 | Id | Salary |
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |


For example, given the above Employee table, the query should return 200 as the second highest salary. If there is no second highest salary, then the query should return null.



 | SecondHighestSalary |
| 200 |


This is a question from Leetcode, for which I entered the following code:



 SELECT CASE WHEN Salary = '' 
THEN NULL
ELSE Salary
END AS SecondHighestSalary
FROM (SELECT TOP 2 Salary
,ROW_NUMBER() OVER (ORDER BY Salary DESC) AS Num
FROM Employee
ORDER BY Salary DESC) AS T
WHERE T.Num = 2


It says that the query does not return NULL if there's no value for second highest salary.
For eg. if the table is



 | Id | Salary| 
| 1 | 100 |


The query should return



 |SecondHighestSalary|
| null |


and not



 |SecondHighestSalary|
| |









share|improve this question
























  • geeksforgeeks.org/sql-query-to-find-second-largest-salary

    – Prasad Telkikar
    Nov 14 '18 at 9:54











  • "Second highest" is ambiguous. What do you want to do in case of a tie? E.g. add another record with salary 300 to your sample table. Then: do you want to show 300 or 200? You must answer this question first, before you can write the query.

    – Thorsten Kettner
    Nov 14 '18 at 10:11












  • @ThorstenKettner even in case of tie, it should display the next highest value, no matter how many times the first highest value is repeated. If no second highest value is present, then it should return NULL.

    – SukuAD
    Nov 14 '18 at 12:30













1












1








1








Write a SQL query to get the second highest salary from the Employee table.



 | Id | Salary |
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |


For example, given the above Employee table, the query should return 200 as the second highest salary. If there is no second highest salary, then the query should return null.



 | SecondHighestSalary |
| 200 |


This is a question from Leetcode, for which I entered the following code:



 SELECT CASE WHEN Salary = '' 
THEN NULL
ELSE Salary
END AS SecondHighestSalary
FROM (SELECT TOP 2 Salary
,ROW_NUMBER() OVER (ORDER BY Salary DESC) AS Num
FROM Employee
ORDER BY Salary DESC) AS T
WHERE T.Num = 2


It says that the query does not return NULL if there's no value for second highest salary.
For eg. if the table is



 | Id | Salary| 
| 1 | 100 |


The query should return



 |SecondHighestSalary|
| null |


and not



 |SecondHighestSalary|
| |









share|improve this question
















Write a SQL query to get the second highest salary from the Employee table.



 | Id | Salary |
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |


For example, given the above Employee table, the query should return 200 as the second highest salary. If there is no second highest salary, then the query should return null.



 | SecondHighestSalary |
| 200 |


This is a question from Leetcode, for which I entered the following code:



 SELECT CASE WHEN Salary = '' 
THEN NULL
ELSE Salary
END AS SecondHighestSalary
FROM (SELECT TOP 2 Salary
,ROW_NUMBER() OVER (ORDER BY Salary DESC) AS Num
FROM Employee
ORDER BY Salary DESC) AS T
WHERE T.Num = 2


It says that the query does not return NULL if there's no value for second highest salary.
For eg. if the table is



 | Id | Salary| 
| 1 | 100 |


The query should return



 |SecondHighestSalary|
| null |


and not



 |SecondHighestSalary|
| |






sql sql-server sql-server-2008 sql-server-2012






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 14 '18 at 10:27







SukuAD

















asked Nov 14 '18 at 9:33









SukuADSukuAD

186




186












  • geeksforgeeks.org/sql-query-to-find-second-largest-salary

    – Prasad Telkikar
    Nov 14 '18 at 9:54











  • "Second highest" is ambiguous. What do you want to do in case of a tie? E.g. add another record with salary 300 to your sample table. Then: do you want to show 300 or 200? You must answer this question first, before you can write the query.

    – Thorsten Kettner
    Nov 14 '18 at 10:11












  • @ThorstenKettner even in case of tie, it should display the next highest value, no matter how many times the first highest value is repeated. If no second highest value is present, then it should return NULL.

    – SukuAD
    Nov 14 '18 at 12:30

















  • geeksforgeeks.org/sql-query-to-find-second-largest-salary

    – Prasad Telkikar
    Nov 14 '18 at 9:54











  • "Second highest" is ambiguous. What do you want to do in case of a tie? E.g. add another record with salary 300 to your sample table. Then: do you want to show 300 or 200? You must answer this question first, before you can write the query.

    – Thorsten Kettner
    Nov 14 '18 at 10:11












  • @ThorstenKettner even in case of tie, it should display the next highest value, no matter how many times the first highest value is repeated. If no second highest value is present, then it should return NULL.

    – SukuAD
    Nov 14 '18 at 12:30
















geeksforgeeks.org/sql-query-to-find-second-largest-salary

– Prasad Telkikar
Nov 14 '18 at 9:54





geeksforgeeks.org/sql-query-to-find-second-largest-salary

– Prasad Telkikar
Nov 14 '18 at 9:54













"Second highest" is ambiguous. What do you want to do in case of a tie? E.g. add another record with salary 300 to your sample table. Then: do you want to show 300 or 200? You must answer this question first, before you can write the query.

– Thorsten Kettner
Nov 14 '18 at 10:11






"Second highest" is ambiguous. What do you want to do in case of a tie? E.g. add another record with salary 300 to your sample table. Then: do you want to show 300 or 200? You must answer this question first, before you can write the query.

– Thorsten Kettner
Nov 14 '18 at 10:11














@ThorstenKettner even in case of tie, it should display the next highest value, no matter how many times the first highest value is repeated. If no second highest value is present, then it should return NULL.

– SukuAD
Nov 14 '18 at 12:30





@ThorstenKettner even in case of tie, it should display the next highest value, no matter how many times the first highest value is repeated. If no second highest value is present, then it should return NULL.

– SukuAD
Nov 14 '18 at 12:30












9 Answers
9






active

oldest

votes


















2














In case of ties you want the second highest distinct value. E.g. for values 100, 200, 300, 300, you want 200.



So get the highest value (MAX(salary) => 300) and then get the highest value less than that:



select max(salary) from mytable where salary < (select max(salary) from mytable);





share|improve this answer






























    1














    you should be able to do that with OFFSET 1/FETCH 1:



    https://technet.microsoft.com/en-us/library/gg699618(v=sql.110).aspx






    share|improve this answer























    • OFFSET/ FETCH helps in returning the second highest value if there are two or more different salaries, but it doesn't help in returning NULL if there's only one value for the salary.

      – SukuAD
      Nov 14 '18 at 11:02


















    1














    You can use RANK() function to rank the values for Salary column.



    SELECT *
    FROM
    (
    SELECT *, RANK()OVER(ORDER BY Salary DESC) As SalaryRank
    FROM Employee
    ) AS Tab
    WHERE SalaryRank = 2





    share|improve this answer























    • Thanks for the answer but if there's no value as the Second Highest, for eg. if there only one row in the master table, then even using rank does not return NULL. It returns ' ' value.

      – SukuAD
      Nov 14 '18 at 10:03



















    1














    SELECT id, MAX(salary) AS salary 
    FROM employee
    WHERE salary IN
    (SELECT salary FROM employee MINUS SELECT MAX(salary)
    FROM employee);


    You can try above code to find 2nd maximum salary.
    The above code uses MINUS operator.
    For further reference use the below links
    https://www.techonthenet.com/sql/minus.php
    https://www.geeksforgeeks.org/sql-query-to-find-second-largest-salary/






    share|improve this answer






























      1














      Here is the easy way to do this



      SELECT MAX(Salary) FROM table WHERE Salary NOT IN (SELECT MAX(Salary) FROM table);





      share|improve this answer






























        0














        I would use DENSE_RANK() & do LEFT JOIN with employee table :



        SELECT t.Seq, e.*
        FROM ( VALUES (2)
        ) t (Seq) LEFT JOIN
        (SELECT e.*,
        DENSE_RANK() OVER (ORDER BY Salary DESC) AS Num
        FROM Employee e
        ) e
        ON e.Num = t.Seq;





        share|improve this answer






























          0














          While you can use a CTE (from MSSQL 2005 or newer) or ROWNUMBER the easiest and more "portable" way is to just order by twice using a subquery.



          select top 1 x.* from
          (select top 2 t1.* from dbo.Employee t1 order by t1.Salary) as x
          order by x.Salary desc


          The requisite to show null when there's not a second bigger salary is a bit more tricky but also easy to do with a if.



          if (select count(*) from dbo.Employee) > 1
          begin
          select top 1 x.* from
          (select top 2 emp.* from dbo.Employee emp order by emp.Salary) as x
          order by x.Salary desc
          end
          else begin
          select null as Id, null as Salary
          end


          Obs:. OP don't said what to do when the second largest is a tie with the first but using this solution is a simple matter of using a DISTINCT in the IF subquery.






          share|improve this answer
































            0














            Query:




            CREATE TABLE a
            ([Id] int, [Salary] int)
            ;

            INSERT INTO a
            ([Id], [Salary])
            VALUES
            (1, 100),
            (2, 200),
            (3, 300)
            ;

            GO
            SELECT Salary as SecondHighestSalary
            FROM a
            ORDER BY Salary
            OFFSET 1 ROWS FETCH NEXT 1 ROWS ONLY



            | SecondHighestSalary |
            | ------------------: |
            | 200 |






            share|improve this answer






























              0














              You can try this for getting n-th highest salary, where n = 1,2,3....(int)



              SELECT TOP 1 salary FROM (
              SELECT TOP n salary
              FROM employees
              ORDER BY salary DESC) AS emp
              ORDER BY salary ASC


              Hope this will help you. Below is one of the implementation.



              create table #salary (salary int)
              insert into #salary values (100), (200), (300)

              SELECT TOP 1 salary FROM (
              SELECT TOP 2 salary
              FROM #salary
              ORDER BY salary DESC) AS emp
              ORDER BY salary ASC

              drop table #salary


              The output is here 200 as 300 is first highest, 200 is second highest and 100 is the third highest as shown below



              salary
              200


              Here n is 2






              share|improve this answer






















                Your Answer






                StackExchange.ifUsing("editor", function ()
                StackExchange.using("externalEditor", function ()
                StackExchange.using("snippets", function ()
                StackExchange.snippets.init();
                );
                );
                , "code-snippets");

                StackExchange.ready(function()
                var channelOptions =
                tags: "".split(" "),
                id: "1"
                ;
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function()
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled)
                StackExchange.using("snippets", function()
                createEditor();
                );

                else
                createEditor();

                );

                function createEditor()
                StackExchange.prepareEditor(
                heartbeatType: 'answer',
                autoActivateHeartbeat: false,
                convertImagesToLinks: true,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: 10,
                bindNavPrevention: true,
                postfix: "",
                imageUploader:
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                ,
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                );



                );













                draft saved

                draft discarded


















                StackExchange.ready(
                function ()
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53296941%2fsecond-highest-salary%23new-answer', 'question_page');

                );

                Post as a guest















                Required, but never shown

























                9 Answers
                9






                active

                oldest

                votes








                9 Answers
                9






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                2














                In case of ties you want the second highest distinct value. E.g. for values 100, 200, 300, 300, you want 200.



                So get the highest value (MAX(salary) => 300) and then get the highest value less than that:



                select max(salary) from mytable where salary < (select max(salary) from mytable);





                share|improve this answer



























                  2














                  In case of ties you want the second highest distinct value. E.g. for values 100, 200, 300, 300, you want 200.



                  So get the highest value (MAX(salary) => 300) and then get the highest value less than that:



                  select max(salary) from mytable where salary < (select max(salary) from mytable);





                  share|improve this answer

























                    2












                    2








                    2







                    In case of ties you want the second highest distinct value. E.g. for values 100, 200, 300, 300, you want 200.



                    So get the highest value (MAX(salary) => 300) and then get the highest value less than that:



                    select max(salary) from mytable where salary < (select max(salary) from mytable);





                    share|improve this answer













                    In case of ties you want the second highest distinct value. E.g. for values 100, 200, 300, 300, you want 200.



                    So get the highest value (MAX(salary) => 300) and then get the highest value less than that:



                    select max(salary) from mytable where salary < (select max(salary) from mytable);






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 14 '18 at 12:36









                    Thorsten KettnerThorsten Kettner

                    51.7k32642




                    51.7k32642























                        1














                        you should be able to do that with OFFSET 1/FETCH 1:



                        https://technet.microsoft.com/en-us/library/gg699618(v=sql.110).aspx






                        share|improve this answer























                        • OFFSET/ FETCH helps in returning the second highest value if there are two or more different salaries, but it doesn't help in returning NULL if there's only one value for the salary.

                          – SukuAD
                          Nov 14 '18 at 11:02















                        1














                        you should be able to do that with OFFSET 1/FETCH 1:



                        https://technet.microsoft.com/en-us/library/gg699618(v=sql.110).aspx






                        share|improve this answer























                        • OFFSET/ FETCH helps in returning the second highest value if there are two or more different salaries, but it doesn't help in returning NULL if there's only one value for the salary.

                          – SukuAD
                          Nov 14 '18 at 11:02













                        1












                        1








                        1







                        you should be able to do that with OFFSET 1/FETCH 1:



                        https://technet.microsoft.com/en-us/library/gg699618(v=sql.110).aspx






                        share|improve this answer













                        you should be able to do that with OFFSET 1/FETCH 1:



                        https://technet.microsoft.com/en-us/library/gg699618(v=sql.110).aspx







                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Nov 14 '18 at 9:36









                        Zdravko DanevZdravko Danev

                        10.3k12541




                        10.3k12541












                        • OFFSET/ FETCH helps in returning the second highest value if there are two or more different salaries, but it doesn't help in returning NULL if there's only one value for the salary.

                          – SukuAD
                          Nov 14 '18 at 11:02

















                        • OFFSET/ FETCH helps in returning the second highest value if there are two or more different salaries, but it doesn't help in returning NULL if there's only one value for the salary.

                          – SukuAD
                          Nov 14 '18 at 11:02
















                        OFFSET/ FETCH helps in returning the second highest value if there are two or more different salaries, but it doesn't help in returning NULL if there's only one value for the salary.

                        – SukuAD
                        Nov 14 '18 at 11:02





                        OFFSET/ FETCH helps in returning the second highest value if there are two or more different salaries, but it doesn't help in returning NULL if there's only one value for the salary.

                        – SukuAD
                        Nov 14 '18 at 11:02











                        1














                        You can use RANK() function to rank the values for Salary column.



                        SELECT *
                        FROM
                        (
                        SELECT *, RANK()OVER(ORDER BY Salary DESC) As SalaryRank
                        FROM Employee
                        ) AS Tab
                        WHERE SalaryRank = 2





                        share|improve this answer























                        • Thanks for the answer but if there's no value as the Second Highest, for eg. if there only one row in the master table, then even using rank does not return NULL. It returns ' ' value.

                          – SukuAD
                          Nov 14 '18 at 10:03
















                        1














                        You can use RANK() function to rank the values for Salary column.



                        SELECT *
                        FROM
                        (
                        SELECT *, RANK()OVER(ORDER BY Salary DESC) As SalaryRank
                        FROM Employee
                        ) AS Tab
                        WHERE SalaryRank = 2





                        share|improve this answer























                        • Thanks for the answer but if there's no value as the Second Highest, for eg. if there only one row in the master table, then even using rank does not return NULL. It returns ' ' value.

                          – SukuAD
                          Nov 14 '18 at 10:03














                        1












                        1








                        1







                        You can use RANK() function to rank the values for Salary column.



                        SELECT *
                        FROM
                        (
                        SELECT *, RANK()OVER(ORDER BY Salary DESC) As SalaryRank
                        FROM Employee
                        ) AS Tab
                        WHERE SalaryRank = 2





                        share|improve this answer













                        You can use RANK() function to rank the values for Salary column.



                        SELECT *
                        FROM
                        (
                        SELECT *, RANK()OVER(ORDER BY Salary DESC) As SalaryRank
                        FROM Employee
                        ) AS Tab
                        WHERE SalaryRank = 2






                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Nov 14 '18 at 9:40









                        akshayakshay

                        617112




                        617112












                        • Thanks for the answer but if there's no value as the Second Highest, for eg. if there only one row in the master table, then even using rank does not return NULL. It returns ' ' value.

                          – SukuAD
                          Nov 14 '18 at 10:03


















                        • Thanks for the answer but if there's no value as the Second Highest, for eg. if there only one row in the master table, then even using rank does not return NULL. It returns ' ' value.

                          – SukuAD
                          Nov 14 '18 at 10:03

















                        Thanks for the answer but if there's no value as the Second Highest, for eg. if there only one row in the master table, then even using rank does not return NULL. It returns ' ' value.

                        – SukuAD
                        Nov 14 '18 at 10:03






                        Thanks for the answer but if there's no value as the Second Highest, for eg. if there only one row in the master table, then even using rank does not return NULL. It returns ' ' value.

                        – SukuAD
                        Nov 14 '18 at 10:03












                        1














                        SELECT id, MAX(salary) AS salary 
                        FROM employee
                        WHERE salary IN
                        (SELECT salary FROM employee MINUS SELECT MAX(salary)
                        FROM employee);


                        You can try above code to find 2nd maximum salary.
                        The above code uses MINUS operator.
                        For further reference use the below links
                        https://www.techonthenet.com/sql/minus.php
                        https://www.geeksforgeeks.org/sql-query-to-find-second-largest-salary/






                        share|improve this answer



























                          1














                          SELECT id, MAX(salary) AS salary 
                          FROM employee
                          WHERE salary IN
                          (SELECT salary FROM employee MINUS SELECT MAX(salary)
                          FROM employee);


                          You can try above code to find 2nd maximum salary.
                          The above code uses MINUS operator.
                          For further reference use the below links
                          https://www.techonthenet.com/sql/minus.php
                          https://www.geeksforgeeks.org/sql-query-to-find-second-largest-salary/






                          share|improve this answer

























                            1












                            1








                            1







                            SELECT id, MAX(salary) AS salary 
                            FROM employee
                            WHERE salary IN
                            (SELECT salary FROM employee MINUS SELECT MAX(salary)
                            FROM employee);


                            You can try above code to find 2nd maximum salary.
                            The above code uses MINUS operator.
                            For further reference use the below links
                            https://www.techonthenet.com/sql/minus.php
                            https://www.geeksforgeeks.org/sql-query-to-find-second-largest-salary/






                            share|improve this answer













                            SELECT id, MAX(salary) AS salary 
                            FROM employee
                            WHERE salary IN
                            (SELECT salary FROM employee MINUS SELECT MAX(salary)
                            FROM employee);


                            You can try above code to find 2nd maximum salary.
                            The above code uses MINUS operator.
                            For further reference use the below links
                            https://www.techonthenet.com/sql/minus.php
                            https://www.geeksforgeeks.org/sql-query-to-find-second-largest-salary/







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Nov 14 '18 at 10:13









                            Balakrishnan BskBalakrishnan Bsk

                            16812




                            16812





















                                1














                                Here is the easy way to do this



                                SELECT MAX(Salary) FROM table WHERE Salary NOT IN (SELECT MAX(Salary) FROM table);





                                share|improve this answer



























                                  1














                                  Here is the easy way to do this



                                  SELECT MAX(Salary) FROM table WHERE Salary NOT IN (SELECT MAX(Salary) FROM table);





                                  share|improve this answer

























                                    1












                                    1








                                    1







                                    Here is the easy way to do this



                                    SELECT MAX(Salary) FROM table WHERE Salary NOT IN (SELECT MAX(Salary) FROM table);





                                    share|improve this answer













                                    Here is the easy way to do this



                                    SELECT MAX(Salary) FROM table WHERE Salary NOT IN (SELECT MAX(Salary) FROM table);






                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Nov 15 '18 at 9:49









                                    Omar HasanOmar Hasan

                                    1285




                                    1285





















                                        0














                                        I would use DENSE_RANK() & do LEFT JOIN with employee table :



                                        SELECT t.Seq, e.*
                                        FROM ( VALUES (2)
                                        ) t (Seq) LEFT JOIN
                                        (SELECT e.*,
                                        DENSE_RANK() OVER (ORDER BY Salary DESC) AS Num
                                        FROM Employee e
                                        ) e
                                        ON e.Num = t.Seq;





                                        share|improve this answer



























                                          0














                                          I would use DENSE_RANK() & do LEFT JOIN with employee table :



                                          SELECT t.Seq, e.*
                                          FROM ( VALUES (2)
                                          ) t (Seq) LEFT JOIN
                                          (SELECT e.*,
                                          DENSE_RANK() OVER (ORDER BY Salary DESC) AS Num
                                          FROM Employee e
                                          ) e
                                          ON e.Num = t.Seq;





                                          share|improve this answer

























                                            0












                                            0








                                            0







                                            I would use DENSE_RANK() & do LEFT JOIN with employee table :



                                            SELECT t.Seq, e.*
                                            FROM ( VALUES (2)
                                            ) t (Seq) LEFT JOIN
                                            (SELECT e.*,
                                            DENSE_RANK() OVER (ORDER BY Salary DESC) AS Num
                                            FROM Employee e
                                            ) e
                                            ON e.Num = t.Seq;





                                            share|improve this answer













                                            I would use DENSE_RANK() & do LEFT JOIN with employee table :



                                            SELECT t.Seq, e.*
                                            FROM ( VALUES (2)
                                            ) t (Seq) LEFT JOIN
                                            (SELECT e.*,
                                            DENSE_RANK() OVER (ORDER BY Salary DESC) AS Num
                                            FROM Employee e
                                            ) e
                                            ON e.Num = t.Seq;






                                            share|improve this answer












                                            share|improve this answer



                                            share|improve this answer










                                            answered Nov 14 '18 at 9:47









                                            Yogesh SharmaYogesh Sharma

                                            31.1k51437




                                            31.1k51437





















                                                0














                                                While you can use a CTE (from MSSQL 2005 or newer) or ROWNUMBER the easiest and more "portable" way is to just order by twice using a subquery.



                                                select top 1 x.* from
                                                (select top 2 t1.* from dbo.Employee t1 order by t1.Salary) as x
                                                order by x.Salary desc


                                                The requisite to show null when there's not a second bigger salary is a bit more tricky but also easy to do with a if.



                                                if (select count(*) from dbo.Employee) > 1
                                                begin
                                                select top 1 x.* from
                                                (select top 2 emp.* from dbo.Employee emp order by emp.Salary) as x
                                                order by x.Salary desc
                                                end
                                                else begin
                                                select null as Id, null as Salary
                                                end


                                                Obs:. OP don't said what to do when the second largest is a tie with the first but using this solution is a simple matter of using a DISTINCT in the IF subquery.






                                                share|improve this answer





























                                                  0














                                                  While you can use a CTE (from MSSQL 2005 or newer) or ROWNUMBER the easiest and more "portable" way is to just order by twice using a subquery.



                                                  select top 1 x.* from
                                                  (select top 2 t1.* from dbo.Employee t1 order by t1.Salary) as x
                                                  order by x.Salary desc


                                                  The requisite to show null when there's not a second bigger salary is a bit more tricky but also easy to do with a if.



                                                  if (select count(*) from dbo.Employee) > 1
                                                  begin
                                                  select top 1 x.* from
                                                  (select top 2 emp.* from dbo.Employee emp order by emp.Salary) as x
                                                  order by x.Salary desc
                                                  end
                                                  else begin
                                                  select null as Id, null as Salary
                                                  end


                                                  Obs:. OP don't said what to do when the second largest is a tie with the first but using this solution is a simple matter of using a DISTINCT in the IF subquery.






                                                  share|improve this answer



























                                                    0












                                                    0








                                                    0







                                                    While you can use a CTE (from MSSQL 2005 or newer) or ROWNUMBER the easiest and more "portable" way is to just order by twice using a subquery.



                                                    select top 1 x.* from
                                                    (select top 2 t1.* from dbo.Employee t1 order by t1.Salary) as x
                                                    order by x.Salary desc


                                                    The requisite to show null when there's not a second bigger salary is a bit more tricky but also easy to do with a if.



                                                    if (select count(*) from dbo.Employee) > 1
                                                    begin
                                                    select top 1 x.* from
                                                    (select top 2 emp.* from dbo.Employee emp order by emp.Salary) as x
                                                    order by x.Salary desc
                                                    end
                                                    else begin
                                                    select null as Id, null as Salary
                                                    end


                                                    Obs:. OP don't said what to do when the second largest is a tie with the first but using this solution is a simple matter of using a DISTINCT in the IF subquery.






                                                    share|improve this answer















                                                    While you can use a CTE (from MSSQL 2005 or newer) or ROWNUMBER the easiest and more "portable" way is to just order by twice using a subquery.



                                                    select top 1 x.* from
                                                    (select top 2 t1.* from dbo.Employee t1 order by t1.Salary) as x
                                                    order by x.Salary desc


                                                    The requisite to show null when there's not a second bigger salary is a bit more tricky but also easy to do with a if.



                                                    if (select count(*) from dbo.Employee) > 1
                                                    begin
                                                    select top 1 x.* from
                                                    (select top 2 emp.* from dbo.Employee emp order by emp.Salary) as x
                                                    order by x.Salary desc
                                                    end
                                                    else begin
                                                    select null as Id, null as Salary
                                                    end


                                                    Obs:. OP don't said what to do when the second largest is a tie with the first but using this solution is a simple matter of using a DISTINCT in the IF subquery.







                                                    share|improve this answer














                                                    share|improve this answer



                                                    share|improve this answer








                                                    edited Nov 14 '18 at 10:06

























                                                    answered Nov 14 '18 at 9:58









                                                    jeanjean

                                                    3,23342339




                                                    3,23342339





















                                                        0














                                                        Query:




                                                        CREATE TABLE a
                                                        ([Id] int, [Salary] int)
                                                        ;

                                                        INSERT INTO a
                                                        ([Id], [Salary])
                                                        VALUES
                                                        (1, 100),
                                                        (2, 200),
                                                        (3, 300)
                                                        ;

                                                        GO
                                                        SELECT Salary as SecondHighestSalary
                                                        FROM a
                                                        ORDER BY Salary
                                                        OFFSET 1 ROWS FETCH NEXT 1 ROWS ONLY



                                                        | SecondHighestSalary |
                                                        | ------------------: |
                                                        | 200 |






                                                        share|improve this answer



























                                                          0














                                                          Query:




                                                          CREATE TABLE a
                                                          ([Id] int, [Salary] int)
                                                          ;

                                                          INSERT INTO a
                                                          ([Id], [Salary])
                                                          VALUES
                                                          (1, 100),
                                                          (2, 200),
                                                          (3, 300)
                                                          ;

                                                          GO
                                                          SELECT Salary as SecondHighestSalary
                                                          FROM a
                                                          ORDER BY Salary
                                                          OFFSET 1 ROWS FETCH NEXT 1 ROWS ONLY



                                                          | SecondHighestSalary |
                                                          | ------------------: |
                                                          | 200 |






                                                          share|improve this answer

























                                                            0












                                                            0








                                                            0







                                                            Query:




                                                            CREATE TABLE a
                                                            ([Id] int, [Salary] int)
                                                            ;

                                                            INSERT INTO a
                                                            ([Id], [Salary])
                                                            VALUES
                                                            (1, 100),
                                                            (2, 200),
                                                            (3, 300)
                                                            ;

                                                            GO
                                                            SELECT Salary as SecondHighestSalary
                                                            FROM a
                                                            ORDER BY Salary
                                                            OFFSET 1 ROWS FETCH NEXT 1 ROWS ONLY



                                                            | SecondHighestSalary |
                                                            | ------------------: |
                                                            | 200 |






                                                            share|improve this answer













                                                            Query:




                                                            CREATE TABLE a
                                                            ([Id] int, [Salary] int)
                                                            ;

                                                            INSERT INTO a
                                                            ([Id], [Salary])
                                                            VALUES
                                                            (1, 100),
                                                            (2, 200),
                                                            (3, 300)
                                                            ;

                                                            GO
                                                            SELECT Salary as SecondHighestSalary
                                                            FROM a
                                                            ORDER BY Salary
                                                            OFFSET 1 ROWS FETCH NEXT 1 ROWS ONLY



                                                            | SecondHighestSalary |
                                                            | ------------------: |
                                                            | 200 |







                                                            share|improve this answer












                                                            share|improve this answer



                                                            share|improve this answer










                                                            answered Nov 14 '18 at 10:13









                                                            JustinJustin

                                                            7,83162339




                                                            7,83162339





















                                                                0














                                                                You can try this for getting n-th highest salary, where n = 1,2,3....(int)



                                                                SELECT TOP 1 salary FROM (
                                                                SELECT TOP n salary
                                                                FROM employees
                                                                ORDER BY salary DESC) AS emp
                                                                ORDER BY salary ASC


                                                                Hope this will help you. Below is one of the implementation.



                                                                create table #salary (salary int)
                                                                insert into #salary values (100), (200), (300)

                                                                SELECT TOP 1 salary FROM (
                                                                SELECT TOP 2 salary
                                                                FROM #salary
                                                                ORDER BY salary DESC) AS emp
                                                                ORDER BY salary ASC

                                                                drop table #salary


                                                                The output is here 200 as 300 is first highest, 200 is second highest and 100 is the third highest as shown below



                                                                salary
                                                                200


                                                                Here n is 2






                                                                share|improve this answer



























                                                                  0














                                                                  You can try this for getting n-th highest salary, where n = 1,2,3....(int)



                                                                  SELECT TOP 1 salary FROM (
                                                                  SELECT TOP n salary
                                                                  FROM employees
                                                                  ORDER BY salary DESC) AS emp
                                                                  ORDER BY salary ASC


                                                                  Hope this will help you. Below is one of the implementation.



                                                                  create table #salary (salary int)
                                                                  insert into #salary values (100), (200), (300)

                                                                  SELECT TOP 1 salary FROM (
                                                                  SELECT TOP 2 salary
                                                                  FROM #salary
                                                                  ORDER BY salary DESC) AS emp
                                                                  ORDER BY salary ASC

                                                                  drop table #salary


                                                                  The output is here 200 as 300 is first highest, 200 is second highest and 100 is the third highest as shown below



                                                                  salary
                                                                  200


                                                                  Here n is 2






                                                                  share|improve this answer

























                                                                    0












                                                                    0








                                                                    0







                                                                    You can try this for getting n-th highest salary, where n = 1,2,3....(int)



                                                                    SELECT TOP 1 salary FROM (
                                                                    SELECT TOP n salary
                                                                    FROM employees
                                                                    ORDER BY salary DESC) AS emp
                                                                    ORDER BY salary ASC


                                                                    Hope this will help you. Below is one of the implementation.



                                                                    create table #salary (salary int)
                                                                    insert into #salary values (100), (200), (300)

                                                                    SELECT TOP 1 salary FROM (
                                                                    SELECT TOP 2 salary
                                                                    FROM #salary
                                                                    ORDER BY salary DESC) AS emp
                                                                    ORDER BY salary ASC

                                                                    drop table #salary


                                                                    The output is here 200 as 300 is first highest, 200 is second highest and 100 is the third highest as shown below



                                                                    salary
                                                                    200


                                                                    Here n is 2






                                                                    share|improve this answer













                                                                    You can try this for getting n-th highest salary, where n = 1,2,3....(int)



                                                                    SELECT TOP 1 salary FROM (
                                                                    SELECT TOP n salary
                                                                    FROM employees
                                                                    ORDER BY salary DESC) AS emp
                                                                    ORDER BY salary ASC


                                                                    Hope this will help you. Below is one of the implementation.



                                                                    create table #salary (salary int)
                                                                    insert into #salary values (100), (200), (300)

                                                                    SELECT TOP 1 salary FROM (
                                                                    SELECT TOP 2 salary
                                                                    FROM #salary
                                                                    ORDER BY salary DESC) AS emp
                                                                    ORDER BY salary ASC

                                                                    drop table #salary


                                                                    The output is here 200 as 300 is first highest, 200 is second highest and 100 is the third highest as shown below



                                                                    salary
                                                                    200


                                                                    Here n is 2







                                                                    share|improve this answer












                                                                    share|improve this answer



                                                                    share|improve this answer










                                                                    answered Dec 3 '18 at 10:33









                                                                    Suraj KumarSuraj Kumar

                                                                    2,1961724




                                                                    2,1961724



























                                                                        draft saved

                                                                        draft discarded
















































                                                                        Thanks for contributing an answer to Stack Overflow!


                                                                        • Please be sure to answer the question. Provide details and share your research!

                                                                        But avoid


                                                                        • Asking for help, clarification, or responding to other answers.

                                                                        • Making statements based on opinion; back them up with references or personal experience.

                                                                        To learn more, see our tips on writing great answers.




                                                                        draft saved


                                                                        draft discarded














                                                                        StackExchange.ready(
                                                                        function ()
                                                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53296941%2fsecond-highest-salary%23new-answer', 'question_page');

                                                                        );

                                                                        Post as a guest















                                                                        Required, but never shown





















































                                                                        Required, but never shown














                                                                        Required, but never shown












                                                                        Required, but never shown







                                                                        Required, but never shown

































                                                                        Required, but never shown














                                                                        Required, but never shown












                                                                        Required, but never shown







                                                                        Required, but never shown







                                                                        這個網誌中的熱門文章

                                                                        Barbados

                                                                        How to read a connectionString WITH PROVIDER in .NET Core?

                                                                        Node.js Script on GitHub Pages or Amazon S3