🔢">
Web & database pagination tool • Offset & query optimization
Pagination is essential for managing large datasets in web applications and databases. Key formulas include:
Proper pagination improves performance by limiting data retrieval and enhancing user experience. For database queries, OFFSET/LIMIT (SQL) or skip/limit (MongoDB) are commonly used.
Example: With 1000 total items and 25 items per page, there are 40 total pages. For page 5, OFFSET = (5-1)*25 = 100, LIMIT = 25, showing records 101-125.
Pagination is a technique to divide large datasets into smaller, manageable chunks. It's essential for web applications and databases to improve performance and user experience.
(Page - 1) × Items Per Page determines starting position.
Calculate total pages and handle edge cases for first/last pages.
Deep pagination with large offsets can significantly slow queries.
If you have 1000 items total and want to display 25 items per page, what is the OFFSET for page 5?
The answer is A) 100. The OFFSET formula is (Page Number - 1) × Items Per Page. For page 5: (5 - 1) × 25 = 4 × 25 = 100. This means the query should skip the first 100 records and return the next 25.
The offset calculation is fundamental to pagination. It determines how many records to skip before retrieving the desired page. The formula subtracts 1 from the page number because pagination is typically 1-indexed (pages start at 1) while array indices are 0-indexed (starting at 0). So for page 1, we skip 0 records; for page 2, we skip 25 records; for page 5, we skip 100 records.
OFFSET: Number of records to skip before returning results
LIMIT: Maximum number of records to return
1-indexed: Starting counting from 1 (like page numbers)
• OFFSET = (Page Number - 1) × Items Per Page
• First page has OFFSET = 0
• Always validate page numbers to prevent errors
• Remember to subtract 1 from page number
• Use parameterized queries to prevent injection
• Always validate that page number is positive
• Forgetting to subtract 1 from page number
• Not validating page parameters
• Not considering zero-indexed vs one-indexed systems
You have 1500 items and want to display 30 items per page. How many total pages will you have, and what records will be on page 7?
Step 1: Calculate total pages = ⌈Total Items / Items Per Page⌉ = ⌈1500 / 30⌉ = ⌈50⌉ = 50 pages
Step 2: Calculate OFFSET for page 7 = (7 - 1) × 30 = 6 × 30 = 180
Step 3: Records on page 7 range from (OFFSET + 1) to (OFFSET + Items Per Page) = (180 + 1) to (180 + 30) = records 181 to 210
Therefore, there will be 50 total pages, and page 7 will show records 181-210.
This problem combines two key pagination calculations. First, we calculate the total number of pages using ceiling division because even if the last page isn't completely filled, it still counts as a page. Second, we calculate the specific range of records on a given page, which requires understanding both the offset and how to translate that to record numbers.
Ceiling Division: Round up to the nearest integer
Record Range: The first and last record numbers on a pagePage Boundary: Where one page ends and another begins
• Total pages = ⌈Total Items / Items Per Page⌉
• Record range = (OFFSET + 1) to (OFFSET + Items Per Page)
• Always use ceiling function for page calculation
• Use Math.ceil() in programming languages
• Remember to add 1 to offset for first record number
• Double-check your math for large datasets
• Using regular division instead of ceiling division
• Forgetting to add 1 to offset for first record number
• Confusing page numbers with record numbers
You're implementing pagination for a social media feed with 1 million posts. A user navigates to page 10,000 (showing 20 posts per page). What performance issue might occur and how can you address it?
The performance issue is that OFFSET 199,980 (from page 10,000 with 20 items per page) forces the database to scan and skip the first 199,980 records before returning the 20 requested records. This causes:
• Slow query execution time
• High CPU and I/O usage
• Poor user experience
Address this by implementing cursor-based pagination using unique identifiers:
Instead of: SELECT * FROM posts ORDER BY timestamp DESC LIMIT 20 OFFSET 199980
Use: SELECT * FROM posts WHERE id < 'last_id_from_previous_page' ORDER BY timestamp DESC LIMIT 20
This avoids scanning through skipped records.
This example demonstrates the fundamental performance problem with traditional offset-based pagination. As page numbers increase, the database must examine and discard more records, making queries progressively slower. Cursor-based pagination solves this by using the value of a unique, indexed column to define the starting point for the next page, eliminating the need to skip records.
Offset-based: Pagination using OFFSET/LIMIT
Cursor-based: Pagination using unique identifiers
Deep Pagination: Accessing pages far into the dataset
• Offset-based pagination degrades with deep pages
• Cursor-based pagination maintains consistent performance
• Always use indexed columns for cursor-based pagination
• Use indexed timestamps or IDs for cursors
• Consider implementing page limits for public APIs
• Monitor query performance for pagination endpoints
• Not considering performance implications of deep pagination
• Using offset-based pagination for large datasets
• Not implementing proper indexing strategies
You need to implement pagination for a MySQL query that sorts results by creation date. How would you write the query for page 3 with 15 items per page? Also, what index should be created for optimal performance?
SQL Query:
Calculation: OFFSET = (3 - 1) × 15 = 30
Recommended Index:
This composite index optimizes both the ORDER BY clause and the WHERE condition. The DESC ordering in the index matches the query's ORDER BY, allowing efficient retrieval of the latest records.
Proper indexing is crucial for pagination performance. The index should match the ORDER BY clause to avoid expensive sorting operations. Including the WHERE clause columns in the index allows for efficient filtering. For this example, we create an index on (created_at DESC, deleted_at) to optimize both the sorting and the filtering condition.
Composite Index: Index on multiple columns
Query Plan: Database execution strategy
Sorting Operation: Arranging records in order
• Index the ORDER BY column for pagination
• Include WHERE clause columns in the index
• Match index ordering with query ordering
• Use EXPLAIN to analyze query performance
• Consider partial indexes for filtered queries
• Test with realistic data volumes
• Not indexing the sort column
• Creating indexes without considering query patterns
• Not accounting for WHERE conditions in index design
Which pagination strategy is most appropriate for an infinite scroll feature on a mobile app with 100,000+ records?
The answer is B) Cursor-based pagination. For infinite scroll with large datasets, cursor-based pagination is optimal because:
• Maintains consistent performance regardless of depth
• Efficient for sequential access patterns
• Reduces server load compared to offset-based pagination
• Works well with mobile app architectures
Traditional offset-based pagination becomes inefficient for deep scrolling, while client-side pagination is unsuitable for 100k+ records.
Different pagination strategies are suited for different use cases. For infinite scroll on mobile apps with large datasets, cursor-based pagination offers the best performance characteristics. It uses unique identifiers to mark the position in the dataset, eliminating the need to skip records as with offset-based pagination. This makes it ideal for sequential access patterns like infinite scroll.
Cursor-based: Uses unique identifiers for navigation
Infinite Scroll: Continuous loading of content
Sequential Access: Accessing data in order
• Use cursor-based for large datasets
• Match pagination strategy to access pattern
• Consider mobile performance constraints
• Use timestamps or IDs as cursors
• Implement proper error handling for gaps
• Consider caching strategies
• Using offset-based for infinite scroll
• Not considering mobile network constraints
• Not handling concurrent data changes
Q: How do I implement infinite scroll with proper pagination?
A: Implement infinite scroll with cursor-based pagination:
Backend: Return a cursor (unique identifier) with each batch of results. The cursor indicates the position after the last returned item.
API Response: {data: [...], cursor: "unique_identifier", hasMore: true}
Frontend: Store the cursor and send it with the next request to fetch the next batch.
Example: After fetching posts 1-10, the backend returns cursor = "post_10_id". When loading more, the frontend sends cursor = "post_10_id" to get posts after post_10_id.
This approach is more efficient than offset-based pagination for large datasets and provides better user experience.
Q: What are the best practices for pagination in high-traffic applications?
A: For high-traffic applications, follow these best practices:
Also, validate all pagination parameters and implement rate limiting to prevent abuse.