← Back to Chapters

MySQL LIMIT & OFFSET

? MySQL LIMIT & OFFSET

? Quick Overview

LIMIT and OFFSET are MySQL clauses used to control how many rows are returned and from which position. In PHP-based applications, they are widely used for pagination and performance optimization.

? Key Concepts

  • LIMIT → Controls maximum number of rows
  • OFFSET → Skips a specific number of rows
  • Commonly used in pagination logic

? Syntax / Theory

? View Code Example
-- Basic LIMIT syntax
SELECT column1, column2
FROM table_name
LIMIT number_of_rows;

? Code Examples

? View Code Example
-- Fetch first 5 employees
SELECT * FROM employees
LIMIT 5;
? View Code Example
-- Skip first 5 rows and fetch next 5
SELECT * FROM employees
LIMIT 5 OFFSET 5;

? Live Output / Explanation

If a table has 20 records, using LIMIT 5 OFFSET 5 will return records from position 6 to 10. This is commonly used when moving between pages.

? Interactive Example (PHP Pagination)

? View Code Example
// PHP pagination using LIMIT and OFFSET
$page = 2;
$limit = 5;
$offset = ($page - 1) * $limit;

$sql = "SELECT * FROM employees LIMIT $limit OFFSET $offset";

? Use Cases

  • Pagination in PHP web applications
  • Displaying limited search results
  • Improving database performance

? Tips & Best Practices

  • Always use ORDER BY with LIMIT for predictable results
  • Use prepared statements in PHP to prevent SQL injection
  • Avoid large OFFSET values on huge datasets

? Try It Yourself

  • Retrieve rows 6–15 from the products table
  • Fetch the first 3 customers older than 30
  • Create a simple pagination system using PHP