MySQL Pagination: OFFSET और Keyset से बड़ी Invoice Lists कैसे संभालें

Invoice या order list में शुरुआत में कुछ सौ records हों तो simple pagination पर्याप्त लगती है। बाद में पुराने records बढ़ने पर page numbers, sorting और filters का behaviour ध्यान माँगता है। सही सवाल सिर्फ यह नहीं कि एक page में कितनी rows दिखानी हैं, बल्कि यह भी है कि अगला page कहाँ से शुरू होगा और records का क्रम किस नियम से तय होगा।

इस guide में OFFSET और keyset pagination को एक छोटी invoice list के उदाहरण से समझेंगे। Example PHP PDO और MySQL को ध्यान में रखता है। कोई benchmark या तय speed improvement का दावा नहीं है; सही चुनाव आपके query plan, dataset और screen की जरूरत पर निर्भर करेगा।

1. Numbered pages के लिए OFFSET समझना आसान है

अगर page size 20 है, तो पहले page का offset zero और दूसरे का 20 होगा। नीचे query दूसरे page के लिए पहली 20 matching rows छोड़कर अगली 20 माँगती है। यह model उन screens में सुविधाजनक है जहाँ user सीधे page number चुनना चाहता है।

Deep pages के लिए offset बड़ा होता जाता है। Query को पहले वाले हिस्से से आगे जाना पड़ता है, इसलिए सिर्फ LIMIT 20 देखकर यह मानना सही नहीं कि हर page में बराबर database work होगा। फिर भी छोटी lists पर OFFSET को बिना measurement हटाना जरूरी नहीं है। पहले अपनी वास्तविक query और response time देखें।

SELECT id, reference, created_at FROM invoices WHERE account_id = 7 ORDER BY created_at DESC, id DESC LIMIT 20 OFFSET 20; -- account_id = 7 is a test value, not a production authorization rule.

2. Sorting में बराबर timestamps का मामला हल करें

केवल ORDER BY created_at DESC लिखने पर एक ही timestamp वाले records का आपसी क्रम तय नहीं रहता। MySQL documentation बताती है कि ORDER BY columns में बराबर values वाली rows अलग execution plans में अलग क्रम में लौट सकती हैं। Pagination के लिए ऐसा अधूरा order भ्रम पैदा कर सकता है।

हम created_at के बाद unique id को tie-breaker रखते हैं। Example में id primary key है और created_at NULL नहीं है। यह deterministic order बनाता है, लेकिन बदलते dataset का frozen snapshot नहीं देता। अगर sort field बाद में edit होती है, तो page traversal के दौरान repeat या skip होने के cases अलग से सोचने होंगे।

ORDER BY created_at DESC, id DESC

3. Keyset अगला page आखिरी दिखाए record से खोजती है

Keyset या cursor pagination में page number के बजाय आखिरी visible row की sorting values रखते हैं। Descending order के इस उदाहरण में अगली query उससे पुराना timestamp या उसी timestamp पर छोटी ID माँगती है। यह पिछले pages की row count पर निर्भर boundary के बजाय record values की boundary है।

दोनों conditions के आसपास parentheses जरूरी हैं, ताकि account filter पूरे boundary expression पर लागू रहे। Account ID authenticated application context से आए। Cursor में account बदल देने से किसी दूसरे account की invoices दिखना स्वीकार्य behaviour नहीं है; हर query में वही access scope दोबारा लागू करें।

SELECT id, reference, created_at FROM invoices WHERE account_id = ?  AND (created_at < ? OR (created_at = ? AND id < ?)) ORDER BY created_at DESC, id DESC LIMIT ?;

4. PHP PDO से next-page query भेजें

नीचे $boundaryTime और $boundaryId पिछले response की आखिरी visible row से आए validated values हैं। Example integer IDs मानता है। Real endpoint में cursor की shape, timestamp format, ID range और active filters validate करें। Query structure fixed रखें; request से मिले column names SQL में सीधे न जोड़ें।

PDO bindValue() में LIMIT को integer bind किया गया है। दोनों timestamp placeholders को अलग positional parameters मिले हैं। इससे named placeholder दोहराने पर driver या emulation behaviour पर निर्भर रहने की जरूरत नहीं पड़ती। Example account ID भी application से मिला authorized integer मानता है।

<?php // Existing configured PDO connection; validated cursor and authorized account. $pageSize = 20; $sql = 'SELECT id, reference, created_at FROM invoices        WHERE account_id = ?          AND (created_at < ? OR (created_at = ? AND id < ?))        ORDER BY created_at DESC, id DESC LIMIT ?'; $statement = $pdo->prepare($sql); $statement->bindValue(1, $accountId, PDO::PARAM_INT); $statement->bindValue(2, $boundaryTime, PDO::PARAM_STR); $statement->bindValue(3, $boundaryTime, PDO::PARAM_STR); $statement->bindValue(4, $boundaryId, PDO::PARAM_INT); $statement->bindValue(5, $pageSize + 1, PDO::PARAM_INT); $statement->execute(); $rows = $statement->fetchAll(PDO::FETCH_ASSOC);

5. एक extra row से next button का फैसला करें

Example 20 के बजाय maximum 21 rows माँगता है। अगर 21वीं row मिली, तो इस result के समय आगे data मौजूद है। UI को केवल पहली 20 दिखाएँ और next cursor आखिरी visible row से बनाएँ। Extra row से cursor बनाने पर वही row अगले page से छूट सकती है। यह application-side pagination convention है।

PDO fetchAll() बाकी result rows array में लाता है। यहाँ query की limit के कारण result छोटा रखा गया है। इसे बड़ी table के सभी records fetch करके PHP में pages काटने की सलाह न समझें। पहले page में boundary condition हटेगी, लेकिन account filter, sorting और pageSize-plus-one convention वही रहेंगे।

<?php $hasNext = count($rows) > $pageSize; $visibleRows = array_slice($rows, 0, $pageSize); $nextCursor = null; if ($hasNext && $visibleRows !== []) {    $lastVisible = $visibleRows[count($visibleRows) - 1];    $nextCursor = [        'created_at' => $lastVisible['created_at'],        'id' => (int) $lastVisible['id'],    ]; } // Encode and validate cursors according to your endpoint's documented contract.

6. Index को filter और order के साथ देखें

इस specific query के लिए account_id, created_at और id वाला composite index review करने लायक candidate है। MySQL multiple-column indexes में column order महत्वपूर्ण है; leftmost prefixes का नियम समझकर design करें। किसी दूसरे search filter को जोड़ने पर वही index हमेशा पर्याप्त हो, यह मानना ठीक नहीं है।

ORDER BY के लिए index का उपयोग query और optimizer की लागत के आकलन पर निर्भर है। इसलिए staging पर EXPLAIN के साथ plan देखें। Index migration blindly production में न चलाएँ; existing indexes, write workload और storage impact भी review करें। केवल keyset query लिख देने से बेहतर performance की guarantee नहीं मिलती।

-- Candidate for review in a test database; not a deployment instruction. CREATE INDEX idx_invoice_account_created_id ON invoices (account_id, created_at, id);

7. Filters बदलें तो cursor का अर्थ भी बदलता है

Date range, status या sort direction बदलने पर पहले page से नई traversal शुरू करना एक साफ UI policy है। पुराने filter का cursor नए result set में reuse करने से user को अप्रत्याशित शुरुआत मिल सकती है। Cursor को opaque string बनाने के बाद भी server-side validation और account permission जरूरी हैं।

Numbered reports में random page access महत्वपूर्ण हो तो OFFSET उपयोगी रह सकता है। Recent activity या next-button list में keyset अधिक natural हो सकती है। Previous-page navigation, exact total count और stable exports अलग requirements हैं; इस next-page example में वे implement नहीं किए गए हैं।

Test checklist और निष्कर्ष

Test fixtures में एक ही timestamp वाली कई rows रखें और दो pages के IDs की तुलना करें। फिर empty list, exactly 20 rows, 21 rows और अंतिम अधूरे page को जाँचें। Traversal के बीच insert या delete होने पर अपना expected behaviour लिखें; ordinary separate requests को consistent export snapshot न मानें।

पहले navigation requirement तय करें, फिर stable order, access scope, cursor contract और index review जोड़ें। अपनी application में query चलाकर correctness और performance दोनों verify करें। Examples समझाने के लिए हैं; आपके schema और deployment की testing का विकल्प नहीं हैं।

  • हर page में वही authorized account scope हो।
  • Cursor आखिरी visible row से बने।
  • Filter बदलने पर पुराना cursor reset हो।
  • Invalid cursor पर controlled error मिले।

Sources / संदर्भ

MySQL PHP Pagination PDO Database Design
← ब्लॉग पर वापस
पढ़ते रहें

और पोस्ट्स

MySQL Backup और Restore Test: Business Website के लिए Practical Guide

MySQL Backup और Restore Test: Business Website के लिए Practical Guide

लेखक:

SQL backup download करने के बाद उसे अलग test environment में restore और verify करने का सरल workflow, जिसमें scope, consistency और recovery planning शामिल हैं।

और पढ़ें →
CodeIgniter 4 Form Validation: सही Input और उपयोगी Error Messages की Guide

CodeIgniter 4 Form Validation: सही Input और उपयोगी Error Messages की Guide

लेखक:

Contact और enquiry forms के लिए explicit input, Strict Rules, validated data और सुरक्षित field errors का practical Hindi workflow.

और पढ़ें →