DataBolt

SQL LEARNING PLATFORM

7

CHAPTER 7

LIMIT & OFFSET

Pagination — how every "Load More" button in every app works.

5

Learning Blocks

SQL

Interactive Queries

In This Chapter

Concepts you'll master

1

LIMIT N - GET only the top N rows

2

LIMIT + OFFSET for page-based pagination

3

The pagination formula every backend engineer uses

9.1 - Top N

SQL QUERY
SELECT name, salary 
FROM employees
ORDER BY salary DESC
LIMIT 3;

9.2 - Pagination with OFFSET

SQL QUERY
-- Page formula: OFFSET = (page_number - 1) * page_size
SELECT name FROM employees
ORDER BY name LIMIT 3 OFFSET 3; -- Page 2

Pro Tip: Always include ORDER BY when using LIMIT/OFFSET. Without ORDER BY, the database returns rows in an arbitrary order — pagination results will be inconsistent and unpredictable across queries.

💡 Engineering Insight: At scale, OFFSET-based pagination is inefficient — to get page 1000 the database still reads 999*page_size rows and throws them away. Senior engineers use 'keyset pagination' (WHERE id > last_seen_id) which is O(1) regardless of page number.

Exercise

Practice your SQL skills

SQL EDITOR
Press semicolon (;) to auto-run query

Tasks

Complete all SQL challenges

1

Show only the first 3 employees.

Current Task
2

Find top 2 highest paid employees.

3

Skip first 2 employees and show next 3 employees.

4

Sort employees by name and show 4 employees after skipping the first one.

5

Find 3 employees with high salaries after skipping top 2 highest paid employees.

Need help solving this task?