MySQL LIMIT
LIMIT restricts how many rows are returned. MySQL does not have TOP like other databases, so we use LIMIT with ORDER BY.
SELECT name, marks FROM students ORDER BY marks DESC LIMIT 3;
Top 3 students
| name | marks |
|---|---|
| Maria | 92 |
| Asha | 88 |
| Robin | 85 |
Read the interview question How to select Top 10 records in MySQL?
OFFSET: skip rows
SELECT name, marks FROM students ORDER BY marks DESC LIMIT 2 OFFSET 2;
Skip 2 rows, then take 2
| name | marks |
|---|---|
| Robin | 85 |
| John | 78 |
A short form is LIMIT 2, 2 (offset first, then count). The long form is easier to read.
Pagination
For a list with 10 rows per page, the page number gives the offset: OFFSET = (page - 1) x 10.
-- page 3, 10 rows per page
SELECT * FROM students ORDER BY id LIMIT 10 OFFSET 20;
The lowest values and one row
SELECT name, marks FROM students ORDER BY marks ASC LIMIT 1;
Result
| name | marks |
|---|---|
| Neha | 45 |
Note:
A big OFFSET is slow, because MySQL still reads and drops all the skipped rows. For very long lists use a “WHERE id > last_seen_id” approach.
Summary
LIMIT nreturns n rows,OFFSET mskips m rows.- Use it with
ORDER BYto get the top or bottom records. - Next: DISTINCT.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |