Forum Discussion
Need SQl help
Hi All
I need help with a SQL problem as desc below
Find the second highest salary from an Employee table without using LIMIT, TOP, or window functions.
Hi powerbidev123 ,
You can use a subquery to find the maximum salary that is lower than the overall maximum salary:
SELECT MAX(salary) AS second_highest_salary FROM Employee WHERE salary < ( SELECT MAX(salary) FROM Employee );The inner query finds the highest salary. The outer query then finds the highest salary below that value, which gives you the second-highest distinct salary.
This also handles duplicate highest salaries correctly.
AI-assisted drafting: AI was used to help structure and phrase this response. I reviewed and validated the technical content before posting.
1 Reply
- ShivekMaharajPower Participant
Hi powerbidev123 ,
You can use a subquery to find the maximum salary that is lower than the overall maximum salary:
SELECT MAX(salary) AS second_highest_salary FROM Employee WHERE salary < ( SELECT MAX(salary) FROM Employee );The inner query finds the highest salary. The outer query then finds the highest salary below that value, which gives you the second-highest distinct salary.
This also handles duplicate highest salaries correctly.
AI-assisted drafting: AI was used to help structure and phrase this response. I reviewed and validated the technical content before posting.