MySQL Nth Highest Value

A common interview question: find the 2nd, 3rd or Nth highest marks. We use the students table with the marks 85, 92, 78, 88, 65 and 45.

Third highest marks

SELECT DISTINCT marks
FROM students
ORDER BY marks DESC
LIMIT 1 OFFSET 2;
Tutorials Class - Output Window
marks
85

For the Nth highest value, use OFFSET N-1. So the 3rd highest uses OFFSET 2, the 2nd highest uses OFFSET 1. DISTINCT makes sure that same marks are counted one time.

Get the student with that marks

SELECT name, marks
FROM students
WHERE marks = (
  SELECT DISTINCT marks
  FROM students
  ORDER BY marks DESC
  LIMIT 1 OFFSET 2
);
Tutorials Class - Output Window
name marks
Robin 85

Note: If there are fewer than N different values, the subquery returns nothing and the result is empty (NULL). Also, more than one student can have the same marks, and all of them are shown.

Related: MySQL LIMIT, DISTINCT and Subqueries.


Learn more about the similar topics:
Tutorials
MySQL JOINs
MySQL Subqueries
MySQL UNION
Exercises & Assignments
Write a query to show the student name who has the second highest marks
Write a query to show the names of students with their course names
Write a query to count the students of each course, including empty courses
Write a query to find the students who scored above the average marks
Interview Questions & Answers
What is the difference between INNER JOIN and LEFT JOIN?
What is the difference between UNION and UNION ALL?
What are the types of JOINs in MySQL?
How to find the second highest marks in MySQL?
What is a subquery in MySQL?