Query to get Second highest number by mark using Order by and LIMIT from student table

preview_player
Показать описание

We can get Second highest number based on the mark of our sample student table. First we will list all the students ( records ) in the order of mark staring from highest to lowest mark.
SELECT * FROM student ORDER BY mark DESC
To this query we will add LIMIT command to restrict the records to 1 only, that will be our highest mark record .
SELECT * FROM student ORDER BY mark DESC LIMIT 0, 1
To get the second highest mark we will change the LIMIT value to return one record starting from 2nd
SELECT * FROM student ORDER BY mark DESC LIMIT 1, 1
To display top three records we will change like this
SELECT * FROM student ORDER BY mark DESC LIMIT 0, 3
We can add WHERE condition to this to restrict the order to a particular class only.
SELECT * FROM student WHERE class=’Three’ ORDER BY mark DESC LIMIT 0, 1
We can get the lowest mark by listing the table in the order of lowest mark to highest mark. We will remove the command DESC.
SELECT * FROM student ORDER BY mark LIMIT 0, 1
Second lowest mark
SELECT * FROM student ORDER BY mark LIMIT 1, 1
Third lowest mark
SELECT * FROM student ORDER BY mark DESC LIMIT 2, 1
We can use RANK() function in MySQL 8 to get rank of the students.
Рекомендации по теме