PHP MySQL Limit Data
In this page:
SELECT * FROM table_name LIMIT count;
SELECT * FROM table_name LIMIT count OFFSET skip; // pagination: OFFSET = (page - 1) * count
Basic LIMIT Usage
Adding LIMIT n to the end of a SELECT statement caps the number of rows returned to at most n, regardless of how many rows actually matched the query -- SELECT * FROM products LIMIT 5 returns at most five products, even if the table holds thousands.
Example: Basic LIMIT Usage
<?php
// Create a new `SQLite3` instance with ':memory:', stored in `$db`
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE products (name TEXT)");
$db->exec("INSERT INTO products VALUES ('A'), ('B'), ('C'), ('D')");
// Declare `$result`, set to `$db->query("SELECT * FROM products LIMIT 2")`
$result = $db->query("SELECT * FROM products LIMIT 2");
// Keep looping while `$row = $result->fetchArray(SQLITE3_ASSOC)` holds
while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
// Print `$row['name'] . "\n"` to the output
echo $row['name'] . "\n";
}
?>
Login to try C/C++/Java/PHP code in the editor
Pagination with LIMIT and OFFSET
LIMIT n OFFSET m skips the first m matching rows, then returns up to n rows after that -- LIMIT 10 OFFSET 20 skips the first 20 rows and returns the next 10, which is exactly how page-based pagination is built: page 3 of a 10-per-page list uses OFFSET 20.
Example: Pagination with LIMIT and OFFSET
<?php
// Create a new `SQLite3` instance with ':memory:', stored in `$db`
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE items (name TEXT)");
foreach (range(1, 30) as $i) { $db->exec("INSERT INTO items VALUES ('Item $i')"); }
// Declare `$result`, set to `$db->query("SELECT * FROM items LIMIT 10 OFFSET 20")`
$result = $db->query("SELECT * FROM items LIMIT 10 OFFSET 20");
// Keep looping while `$row = $result->fetchArray(SQLITE3_ASSOC)` holds
while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
// Print `$row['name'] . "\n"` to the output
echo $row['name'] . "\n";
}
?>
Login to try C/C++/Java/PHP code in the editor
Building a Full Pagination Script
A complete pagination setup needs two pieces of information beyond the page data itself: the total row count (via a separate COUNT query) to calculate the total number of pages, and the current page's slice of results using LIMIT/OFFSET -- together enabling "Page 3 of 12" style navigation controls.
Example: Building a Full Pagination Script
<?php
// Create a new `SQLite3` instance with ':memory:', stored in `$db`
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE items (name TEXT)");
foreach (range(1, 25) as $i) { $db->exec("INSERT INTO items VALUES ('Item $i')"); }
// Declare `$total`, set to `$db->querySingle("SELECT COUNT(*) FROM items")`
$total = $db->querySingle("SELECT COUNT(*) FROM items");
// Declare `$perPage`, set to `10`
$perPage = 10;
// Declare `$totalPages`, set to `ceil($total / $perPage)`
$totalPages = ceil($total / $perPage);
// Print "Page 1 of $totalPages" to the output
echo "Page 1 of $totalPages";
?>
Login to try C/C++/Java/PHP code in the editor
Using LIMIT for Top-N Queries
Beyond pagination, LIMIT combined with ORDER BY is the standard way to answer "top N" questions -- the 3 highest-paid employees, the 10 best-selling products, the 5 most recent comments -- by sorting in the direction that puts the desired rows first, then limiting to just that count.
Example: Using LIMIT for Top-N Queries
<?php
// Create a new `SQLite3` instance with ':memory:', stored in `$db`
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE employees (name TEXT, salary INTEGER)");
$db->exec("INSERT INTO employees VALUES ('Alice', 90000), ('Bob', 70000), ('Carol', 85000)");
// Declare `$result`, set to `$db->query("SELECT * FROM employees ORDER BY salary DESC LIMIT 2")`
$result = $db->query("SELECT * FROM employees ORDER BY salary DESC LIMIT 2");
// Keep looping while `$row = $result->fetchArray(SQLITE3_ASSOC)` holds
while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
// Print `$row['name'] . "\n"` to the output
echo $row['name'] . "\n";
}
?>
Login to try C/C++/Java/PHP code in the editor
Performance Considerations with LIMIT
LIMIT alone with no OFFSET is efficient since the database can stop scanning as soon as it has found enough matching rows -- but a large OFFSET forces it to still count past every skipped row first, which is worth keeping in mind for deep pagination (like page 500 of a huge table).
Example: Performance Considerations with LIMIT
<?php
// Create a new `SQLite3` instance with ':memory:', stored in `$db`
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE items (name TEXT)");
foreach (range(1, 1000) as $i) { $db->exec("INSERT INTO items VALUES ('Item $i')"); }
// Declare `$start`, set to `microtime(true)`
$start = microtime(true);
$db->query("SELECT * FROM items LIMIT 10")->fetchArray();
// Print "Small offset: " . round(microtime(true) - $start, 5) . "s" to the output
echo "Small offset: " . round(microtime(true) - $start, 5) . "s";
?>
Login to try C/C++/Java/PHP code in the editor
- Fetching every row from the database and then slicing the results down to a page's worth in PHP, when LIMIT in the SQL itself is far more efficient and never transfers unneeded rows.
- Forgetting to combine LIMIT with ORDER BY, since without an explicit sort, which rows LIMIT happens to return first is not guaranteed to be meaningful or consistent.
- Calculating a pagination OFFSET incorrectly, like using the current page number directly instead of (page - 1) * pageSize, producing an off-by-one-page result.
- LIMIT n restricts a query to return at most n rows.
- LIMIT n OFFSET m skips the first m rows and then returns up to n rows after that, the basis of page-based pagination.
- LIMIT should almost always be paired with ORDER BY, since the specific rows returned without an explicit sort are not guaranteed to be meaningful.
LIMIT (and OFFSET) are standard SQL and work identically across all MySQL and MariaDB versions PHP supports.
Chapter Quiz — Complete all 21 topics to unlock
0/21 topics done
Complete these topics first:
- PHP MySQL Introduction
- PHP MySQLi Connection
- PHP PDO Introduction
- PHP CRUD Operations
- PHP Prepared Statements
- PHP Stored Procedures
- PHP Transactions
- PHP Error Handling in DB
- PHP MySQL Connect
- PHP MySQL Create DB
- PHP MySQL Create Table
- PHP MySQL Insert Data
- PHP MySQL Get Last ID
- PHP MySQL Insert Multiple
- PHP MySQL Prepared Statements
- PHP MySQL Select Data
- PHP MySQL Where
- PHP MySQL Order By
- PHP MySQL Delete Data
- PHP MySQL Update Data
- PHP MySQL Limit Data