Skip to content

Instantly share code, notes, and snippets.

@bsullins
Created October 2, 2018 21:59
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bsullins/69b5990a995294c48c93780d742fa7e5 to your computer and use it in GitHub Desktop.
Save bsullins/69b5990a995294c48c93780d742fa7e5 to your computer and use it in GitHub Desktop.
How to find the second highest paid employee in a database - this was tested using SQL Server
create table #employees (id int, salary int)
insert into #employees VALUES (1, 100);
insert into #employees VALUES (2, 200);
insert into #employees VALUES (3, 300);
-- first get rank
select id, salary, RANK() OVER (ORDER BY Salary DESC) as SalaryRank
from #employees
-- next choose 2nd highest
select * from (
select id, salary, RANK() OVER (ORDER BY Salary DESC) as SalaryRank
from #employees) a
where SalaryRank = 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment