✏️ Explanatory Question

What is the LIMIT clause and how is it used for pagination?

👁 5 Views
📘 Detailed Answer
🟢 Easy
💡

Answer with Explanation

26

What is the LIMIT clause and how is it used for pagination?

Level: Intermediate — Crucial for building paginated APIs and controlling large result sets.

The LIMIT clause restricts the number of rows returned by a query. It is one of the most useful clauses for performance, previews, and building pagination ("page 1, page 2...") in applications.

LIMIT accepts one or two arguments:

  • LIMIT count: Returns the first count rows.
  • LIMIT offset, count: Skips offset rows, then returns count rows.
Key point: The offset is zero-basedLIMIT 0, 10 returns rows 1–10, and LIMIT 10, 10 returns rows 11–20. You can also write it as LIMIT 10 OFFSET 10.

Pagination Formula

To fetch a specific page, calculate the offset from the page number and page size:

$$ offset = (page\_number - 1) \times page\_size $$

Pagination in Action (page size = 10)

Page Offset LIMIT Clause Rows Returned
1 0 LIMIT 0, 10 1–10
2 10 LIMIT 10, 10 11–20
3 20 LIMIT 20, 10 21–30

Quick Example

-- Return only the first 5 rows
SELECT * FROM employees LIMIT 5;

-- Skip 10 rows, then return 10 (page 2)
SELECT * FROM employees LIMIT 10, 10;

-- Same using OFFSET syntax
SELECT * FROM employees LIMIT 10 OFFSET 10;

-- Pagination with sorting (always sort for consistent pages)
SELECT id, name FROM employees
ORDER BY id
LIMIT 20, 10;    -- page 3

-- Top 3 highest-paid employees
SELECT name, salary FROM employees
ORDER BY salary DESC
LIMIT 3;
Performance tip: Large offsets (e.g., LIMIT 1000000, 10) are slow because MySQL still scans all skipped rows. For deep pagination, use keyset pagination (e.g., WHERE id > last_seen_id ORDER BY id LIMIT 10) instead.
Interviewer tip: The one-liner they want — "LIMIT restricts the number of returned rows. With an offset (LIMIT offset, count) it powers pagination — but always pair it with ORDER BY for consistent results."