DataBolt

All Lessons

Introduction to SQL
SQL Lesson 1: Your Sample Database
SQL Lesson 2: SELECT — Reading data
SQL Lesson 3: WHERE — Filtering rows
SQL Lesson 4: AND, OR, NOT
SQL Lesson 5: BETWEEN, IN, LIKE
SQL Lesson 6: NULL — The Mystery Value
SQL Lesson 7: ORDER BY
SQL Lesson 8: LIMIT & OFFSET
SQL Lesson 9: Aggregate Functions
SQL Lesson 10: GROUP BY
SQL Lesson 11: HAVING
SQL Lesson 12: INNER JOINs
SQL Lesson 13: LEFT JOINs
SQL Lesson 14: RIGHT JOINs
SQL Lesson 15: SELF JOINs
SQL Lesson 16: UNION JOINs
SQL Lesson 17: Joining Multiple Tables
SQL Lesson 18: Subqueries
SQL Lesson 19: CTEs (WITH)
SQL Lesson 20: CASE Statements
SQL Lesson 21: Window Functions
SQL Lesson 22: String Functions
SQL Lesson 23: Date & Time Functions
SQL Lesson 24: INSERT, UPDATE, DELETE
SQL Lesson 25: CREATE TABLE & DDL
SQL Lesson 26: Indexes & Performance
SQL Lesson 27: Transactions & ACID
SQL Lesson 28: SQL Execution Order
SQL Lesson 29: 50 Practice Problems

CHAPTER 9

LIMIT & OFFSET

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

IN THIS CHAPTER

  • LIMIT N - GET only the top N rows
  • LIMIT + OFFSET for page-based pagination
  • The pagination formula every backend engineer uses

9.1 - Top N

Top 3 earners

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

9.2 - Pagination with OFFSET

Page 2 of employees (3 per page)

-- 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 👇

Exercise:

Tasks

1.👉Show only the first 3 employees.
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.
Stuck? Read this task's