To get a second record after sorting, combine ORDER BY with LIMIT. If you need the second distinct value when ties are possible, use a subquery or DENSE_RANK().
LIMIT 1 OFFSET 1 returns the second row, while a distinct-value method finds the next lower mark.
Sort by mark from high to low and return one row. Adding id as a tie-breaker makes row order deterministic when marks are equal.
SELECT id, name, class, mark
FROM student
WHERE class = 'Six'
ORDER BY mark DESC, id ASC
LIMIT 1;
| id | name | class | mark |
|---|---|---|---|
| 33 | Kenn Rein | Six | 96 |
MySQL offsets start at zero. Skip the first sorted row and return one row:
SELECT id, name, class, mark
FROM student
WHERE class = 'Six'
ORDER BY mark DESC, id ASC
LIMIT 1 OFFSET 1;
| id | name | class | mark |
|---|---|---|---|
| 12 | Recky | Six | 94 |
SELECT id, name, class, mark
FROM student
WHERE class = 'Six'
ORDER BY mark DESC, id ASC
LIMIT 3;
| id | name | class | mark |
|---|---|---|---|
| 33 | Kenn Rein | Six | 96 |
| 12 | Recky | Six | 94 |
| 11 | Ronald | Six | 89 |
This version finds the next lower mark even when several rows are tied at the maximum:
SELECT MAX(mark) AS second_highest_mark
FROM student
WHERE class = 'Six'
AND mark < (
SELECT MAX(mark)
FROM student
WHERE class = 'Six'
);
To return the complete student row or rows having that second distinct mark:
SELECT id, name, class, mark
FROM student
WHERE class = 'Six'
AND mark = (
SELECT MAX(mark)
FROM student
WHERE class = 'Six'
AND mark < (
SELECT MAX(mark)
FROM student
WHERE class = 'Six'
)
)
ORDER BY id;
On MySQL 8+, DENSE_RANK() is often the clearest method when you want ranking by distinct values.
WITH ranked AS (
SELECT id, name, class, mark,
DENSE_RANK() OVER (
PARTITION BY class
ORDER BY mark DESC
) AS mark_rank
FROM student
)
SELECT id, name, class, mark
FROM ranked
WHERE class = 'Six'
AND mark_rank = 2
ORDER BY id;
Reverse the sort direction and skip the first row:
SELECT id, name, class, mark
FROM student
WHERE class = 'Six'
ORDER BY mark ASC, id ASC
LIMIT 1 OFFSET 1;
| Requirement | Recommended approach |
|---|---|
| Second row after sorting | ORDER BY ... LIMIT 1 OFFSET 1 |
| Second distinct value | MAX() subquery or DENSE_RANK() |
| Top N rows | ORDER BY ... LIMIT N |
| All rows tied at rank 2 | DENSE_RANK() |
For large tables, index the columns commonly used for filtering and ordering, and make the ORDER BY deterministic when ties matter.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.