MySQL Pagination Query with LIMIT and OFFSET

Pagination means showing the records in small pages, like 10 results on each page. In MySQL we do it with LIMIT and OFFSET.

Formula

OFFSET = (page_number - 1) * records_per_page

Example: page 2, 2 students on each page

SELECT name, city, marks
FROM students
ORDER BY marks DESC
LIMIT 2 OFFSET 2;

The students ordered by marks are Maria (92), Asha (88), Robin (85), John (78), Vikram (65) and Neha (45). Page 1 has the first two, so page 2 skips two rows and shows the next two:

Tutorials Class - Output Window
name city marks
Robin Delhi 85
John Pune 78

Short form

SELECT name, city, marks
FROM students
ORDER BY marks DESC
LIMIT 2, 2;   -- LIMIT offset, row_count
Note: Always use ORDER BY with pagination. Without it, the order of rows is not fixed and the same row can appear on two pages. In PHP, send the page number from the URL and calculate the offset with the formula, and use a prepared statement.

Related: MySQL LIMIT and ORDER BY.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.