MySQL Limit Data
LIMIT clause MySQL में records की संख्या को control करने के लिए उपयोग किया जाता है। PHP
में LIMIT का उपयोग
डेटा को छोटे भागों में fetch करने, pagination बनाने, load कम करने और performance बढ़ाने के लिए
किया जाता है।
यह clause database queries को efficient बनाता है, खासकर जब table में हजारों records हों।
- LIMIT X → पहले X records return करेगा।
- LIMIT X, Y → X records skip करेगा और अगले Y records return करेगा (pagination में उपयोगी)।
- LIMIT का उपयोग हमेशा SELECT query के साथ होता है।
LIMIT कब उपयोग किया जाता है?
- Pagination (जैसे: Page 1, Page 2, Page 3)
- Preview data (top 5, top 10 records)
- Random user listing में कुछ ही users दिखाना
- Server load कम करने के लिए
LIMIT का Basic Syntax
Important Notes
- Note: LIMIT के साथ हमेशा
ORDER BYउपयोग करें ताकि results हर बार एक ही pattern में आएँ। - Warning: बिना ORDER BY के LIMIT random results दे सकता है (खासकर production DB में)।
- Pagination के लिए
LIMIT start, countवाला तरीका सबसे ज्यादा used है।
MySQLi Procedural Example (LIMIT)
यह example students टेबल के पहले 5 records fetch करता है:
Pagination Example (MySQLi)
यह example pagination (page → 1,2,3...) बनाने में उपयोग होता है।
PDO Example (LIMIT)
PDO में LIMIT use करना बहुत आसान है:
PDO Pagination Example
Best Practices for LIMIT
- Always use ORDER BY ताकि results stable रहें।
- Pagination में LIMIT offset method उपयोग करें।
- Large tables के लिए LIMIT slow हो सकता है → INDEX create करें।
- API responses में हमेशा LIMIT का उपयोग करें (overload रोकने के लिए)।
Common Mistakes (and Fixes)
- गलती 1: OFFSET को गलत calculate करना → हमेशा
(page-1)*limitformula लागू करें। - गलती 2: LIMIT के बिना सारा data load कर लेना → Slow + heavy load।
- गलती 3: ORDER BY न लगाना → हर बार different results।
Conclusion
LIMIT MySQL का एक powerful clause है जो performance optimization, user experience (pagination) और resource management के लिए आवश्यक है। PHP में इसे MySQLi और PDO दोनों में आसानी से उपयोग किया जा सकता है। हमेशा ORDER BY और LIMIT साथ में उपयोग करें ताकि results consistent मिलें।
