Can anyone explain me how this query will work and find nth highest salary from salary table.
SELECT salary FROM salary_master s1
WHERE (n-1) = (SELECT COUNT(*) FROM salary_master WHERE salary > s1.salary)
I mean, this query will iterate through all values?
Help me.
The subquery will count ‘how many elements have bigger salary then the current element’. Then your main query checks if the current element in the table has n-1 elements that have bigger salary.
For example, for n = 5, the query will search for an element where 4 other elements have higher salary. Thus it will find the 5th highest.
This is not the best way to do this, though. Consider using ORDER BY and LIMIT …