← Back to PHP Course | Chapter 11: Database | Lesson 21 of 21

PHP MySQL Limit Data

एक million rows वाली एक table अगर एक साथ सबको return करे तो database और results दिखाने वाली चीज़ दोनों को overwhelm कर देगी -- LIMIT किसी query को सिर्फ एक specific संख्या में rows return करने तक cap करता है, pagination (प्रति page 20 results दिखाना) और "top N" style queries (सबसे recent 5 orders) की foundation।
Syntax
php
SELECT * FROM table_name LIMIT count;
SELECT * FROM table_name LIMIT count OFFSET skip;   // pagination: OFFSET = (page - 1) * count

Basic LIMIT Usage

किसी SELECT statement के अंत में LIMIT n add करना return होने वाली rows की संख्या को ज़्यादा से ज़्यादा n तक cap कर देता है, चाहे query से actually कितनी भी rows match हुई हों -- SELECT * FROM products LIMIT 5 ज़्यादा से ज़्यादा पाँच products return करता है, भले ही table हज़ारों रखती हो।

उदाहरण: Basic LIMIT Usage

php
<?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";
}
?>

LIMIT और OFFSET से Pagination

LIMIT n OFFSET m पहली m matching rows skip करता है, फिर उसके बाद n तक rows return करता है -- LIMIT 10 OFFSET 20 पहली 20 rows skip करता है और अगली 10 return करता है, जो exactly है कि page-based pagination कैसे बनाया जाता है: प्रति-page 10 वाली list का page 3 OFFSET 20 इस्तेमाल करता है।

उदाहरण: Pagination with LIMIT and OFFSET

php
<?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";
}
?>

एक पूरी Pagination Script बनाना

एक complete pagination setup को खुद page data से आगे दो जानकारी चाहिए: total pages की संख्या calculate करने के लिए total row count (एक अलग COUNT query के through), और LIMIT/OFFSET इस्तेमाल करके current page के results की slice -- साथ में "Page 3 of 12" style navigation controls enable करते हुए।

उदाहरण: Building a Full Pagination Script

php
<?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";
?>

Top-N Queries के लिए LIMIT इस्तेमाल करना

Pagination से आगे, ORDER BY के साथ combined LIMIT "top N" questions के जवाब देने का standard तरीका है -- सबसे ज़्यादा paid 3 employees, सबसे best-selling 10 products, सबसे recent 5 comments -- उस direction में sort करके जो desired rows को पहले लाए, फिर सिर्फ उस count तक limit करके।

उदाहरण: Using LIMIT for Top-N Queries

php
<?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";
}
?>

LIMIT के साथ Performance Considerations

बिना OFFSET के अकेला LIMIT efficient है क्योंकि database पर्याप्त matching rows मिलते ही scan करना रोक सकता है -- लेकिन एक बड़ा OFFSET इसे पहले हर skipped row से आगे count करने पर मजबूर करता है, जो deep pagination के लिए ध्यान रखने योग्य है (जैसे एक बड़ी table का page 500)।

उदाहरण: Performance Considerations with LIMIT

php
<?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";
?>
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. database से हर row fetch करना और फिर PHP में एक page के लायक तक results slice करना, जबकि खुद SQL में LIMIT कहीं ज़्यादा efficient है और कभी unneeded rows transfer नहीं करता।
  2. LIMIT को ORDER BY के साथ combine करना भूल जाना, क्योंकि बिना एक explicit sort के, LIMIT कौन सी rows पहले return करे इसकी meaningful या consistent होने की guarantee नहीं है।
  3. pagination का OFFSET गलत calculate करना, जैसे (page - 1) * pageSize के बजाय सीधे current page number इस्तेमाल करना, एक off-by-one-page result produce करते हुए।
चैप्टर सारांश
  • LIMIT n किसी query को ज़्यादा से ज़्यादा n rows return करने तक restrict करता है।
  • LIMIT n OFFSET m पहली m rows skip करता है और फिर उसके बाद n तक return करता है, page-based pagination का आधार।
  • LIMIT को लगभग हमेशा ORDER BY के साथ pair किया जाना चाहिए, क्योंकि बिना एक explicit sort के return की गई specific rows की meaningful होने की guarantee नहीं है।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.