Page large results with the right index
Keep queries predictable as a table grows.
Start with access patterns
Write down the filters and sort order the page actually uses. A list of a user's newest applications needs an owner filter and a stable order. An index on the sort column alone may still scan many other users' rows. Inspect a query plan using realistic row counts rather than trusting a small development database.
Choose a stable page boundary
Offset pagination is simple but deep pages get expensive and inserts can shift results between pages. Cursor pagination uses the last seen ordering values. Include a unique tie-breaker so rows sharing a timestamp have a deterministic order. Select only the fields needed for the list view.
$applications = Application::where('user_id', $user->id)
->orderByDesc('created_at')->orderByDesc('id')
->cursorPaginate(20);
Verify correctness and speed
Seed rows with identical timestamps and confirm none are repeated or skipped when moving between pages. Measure query time and inspect the index used in the database engine you deploy. Pagination does not replace authorization; scope to the signed-in user before applying sorting or cursor values.
Check your understanding
Why add a unique tie-breaker to a timestamp sort for cursor pagination?
Show explanation
Rows can share the same timestamp. A unique second key gives a stable total order and prevents skipped or repeated rows.
You can read for free. Create an account to save your progress.
← Previous lesson: Reason about SQL result shapes Next lesson: Connect a database change to a reliable side effect →Put this lesson into practice
A practice activity at this level in the same module.
Try: Diagnose and remove an N+1 queryFurther reading
Primary references for this module. Check the current version when behavior or framework guidance may have changed.