I am using MySQL, I have 50 records in employee table. I want to find the person with the 22nd highest salary.
5 Answers
Use LIMIT
, specifying both an offset and a row count.
To get the 22nd ranked person in order of highest salary, do:
SELECT person
FROM employee
ORDER BY salary DESC
LIMIT 21, 1
Notice the use of 21
here. This is because the offset of the initial row (1st highest salary) is actually 0. Therefore the 22nd highest salary will actually be an offset of 21 (the 21st row in 0-based counting, or "skip 21 rows").
To get the person(s) with the 22nd highest salary, you will need one more level of indirection. Try:
SELECT person
FROM employee
WHERE salary = (
SELECT DISTINCT salary
FROM employee
ORDER BY salary DESC
LIMIT 21, 1
)

- 113,939
- 20
- 158
- 187
-
-
-
-
-
thank you so much for helping me on this. it worked for me. great efforts – Gopal Oct 11 '18 at 19:43
here's another one, considering you have duplicate salary number. I guess limit won't correct solve your case if you have some duplicates. Try something like this,
SELECT aa.*
FROM table1 aa
INNER JOIN
(
SELECT @row:=@row+1 rankNo,
a.Salary
FROM (SELECT DISTINCT Salary FROM table1) a,
(SELECT @row:=0) s
ORDER BY Salary DESC
) bb ON aa.Salary = bb.Salary AND
bb.rankNo = 2
consider you have records like this,
CREATE TABLE Table1
(`EmpID` int, `Salary` int);
INSERT INTO Table1
(`EmpID`, `Salary`)
VALUES
(1, 10),
(2, 12), -- duplicate
(3, 11),
(4, 12), -- duplicate
(5, 14),
(6, 12); -- duplicate
╔═══════╦════════╗
║ EMPID ║ SALARY ║
╠═══════╬════════╣
║ 1 ║ 10 ║
║ 2 ║ 12 ║
║ 3 ║ 11 ║ -- you want to get this value (*2nd from the last value*)
║ 4 ║ 12 ║
║ 5 ║ 14 ║
║ 6 ║ 12 ║
╚═══════╩════════╝

- 258,903
- 69
- 498
- 492
SELECT MIN(salary) FROM (
SELECT DISTINCT salary FROM employee ORDER BY salary DESC LIMIT 22
) limited_salary

- 3,267
- 2
- 21
- 22

- 11
- 2
Just answered a similar question here: select all rows except the four most recent
In your case, you'll want to LIMIT to 1, and OFFSET to the 22 position.