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 n returns n rows, OFFSET m skips m rows.
  • Use it with ORDER BY to get the top or bottom records.
  • Next: DISTINCT.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
Write a query to get data of selected columns from a table
Write a query to select the student with the maximum marks
Write a query to select top 3 students by marks
Write a query to select the rows if a column has no value
Write a query to find the names of students that begin with ‘A’
Write a query to fetch the top 2 records
Interview Questions & Answers
How to select Top 10 records in MySQL?
Write a MySQL query to select students with less than 50% marks
Write a MySQL query to select students with marks between 70 and 80
Write a query to fetch top N records
Write a query to find the names of employees that begin with ‘S’
Write a query to select if column has no/empty value
What is NULL in MySQL? Is NULL the same as 0 or an empty string?