Class 20 of 58 • Data Manipulation & Querying (DML & DQL)

SQL LIMIT & OFFSET: Result Paging & Top N Records

When building web applications, blogs, and mobile apps, loading thousands of records on a single page freezes browsers and drains server memory. The LIMIT and OFFSET clauses allow developers to slice query results into manageable pages (e.g., 10 or 25 records per page) and retrieve top-ranking items.


1. Retrieving Top N Records with LIMIT

To retrieve only the top 3 highest-performing students across the entire university:

SELECT student_id, first_name, gpa
FROM students
ORDER BY gpa DESC
LIMIT 3;

2. Implementing Pagination with OFFSET

• LIMIT: Specifies the maximum number of rows to return.

• OFFSET: Specifies the number of rows to skip before beginning to return records.

Pagination Syntax:
SELECT column_list
FROM table_name
ORDER BY sort_column
LIMIT page_size OFFSET (page_number - 1) * page_size;
-- Page 1: 10 items per page (rows 1 - 10)
SELECT student_id, first_name, gpa
FROM students
ORDER BY student_id ASC
LIMIT 10 OFFSET 0;

-- Page 2: 10 items per page (rows 11 - 20)
SELECT student_id, first_name, gpa
FROM students
ORDER BY student_id ASC
LIMIT 10 OFFSET 10;
Critical Ordering Rule: Never use LIMIT or OFFSET without an explicit ORDER BY clause! Without ORDER BY, the database does not guarantee consistent row ordering between page clicks.

Next, let us learn how to modify existing records safely using the SQL UPDATE Statement!


Frequently Asked Questions (FAQ)

OFFSET = (PageNumber - 1) * PageSize. For example, for Page 3 with 10 records per page: OFFSET = (3 - 1) * 10 = 20.

Because the database engine must still retrieve and sort all 1,000,010 records in memory, and then discard the first 1,000,000 rows. For massive datasets, developers use Keyspace/Cursor Pagination (WHERE id > last_seen_id) instead.

The official ANSI SQL standard uses FETCH FIRST N ROWS ONLY (e.g., OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY).

Next Step in Your SQL Database Learning Path:

Proceed to the next class in sequence to build production mastery of relational database architecture.

Continue to Class 21: UPDATE Statement → Previous: ← ORDER BY Clause | Full Syllabus


Related SQL Masterclass Lessons & Recommended Next Topics

Deterministic Sorting →

Why ORDER BY is strictly mandatory when using LIMIT/OFFSET.

SELECT Queries →

Querying and displaying paginated records in web apps.

Optimizing Deep Pagination →

Keyset pagination (seek method) to avoid massive OFFSET lag.

ROW_NUMBER Pagination →

Using window functions for enterprise row-partitioned ranking.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Reddit

You may also like this!