second highest salary in table in sql
select * from emp e where
2 =(select count(distinct sal) from emp where e.sal<=sal)
I am unable to understand this query…can anyone help me.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Let’s analyze the inner query: you are selecting all the distinct salaries there are more or equal than a predefined salary, which is the salary of the outer query.
So, for EVERY row, you are searching and counting all the other rows with a salary greater or equal that one, and you finally select the one which have a value of 2, which is exactly the second highest salary (because the second highest salary has just 2 salary greater or equal itself: the greater salary at all, and itself).
Tremendous inefficent, because for every row you re-scan the entire table, but funny 🙂