Consider a table with two columns: mark
and name
I need to get the second highest value, and the name of the second highest value.
Consider a table with two columns: mark
and name
I need to get the second highest value, and the name of the second highest value.
You can use ROW_NUMBER(), RANK(), DENSE_RANK() functions in SQL. But in this case, you'll have to use DENSE_RANK() because there may be a condition where 2 or more students may have scored maximum marks, in such case you can't use ROW_NUMBER() or RANK().
Learn more about this functions click here
SELECT * FROM (
SELECT name, mark, DENSE_RANK() over (order by mark desc) RankNo
FROM tablename
) AS Result
WHERE Result.RankNo = 2
SELECT *
FROM (SELECT name,
mark,
Row_number() over(ORDER BY mark DESC) AS rownums
FROM employees)
WHERE rownums = 2;
SELECT name,mark FROM table ORDER BY mark desc limit 1,1
This code sort all records by mark
in descending order. limit 1,1
skips the first result (first 1
= first record) and then returns the next result (second 1
= second record).