Skip to content

Checking your reading list…

Retry

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Databases 31 min read

MySQL Deep Pagination: Cursor, Deferred Join & Export Strategies for Million-Row Tables

This article explains why MySQL LIMIT offset queries become slow at scale, detailing deferred joins, cursor pagination with composite keys, secure cursor encoding, streaming exports, Elasticsearch search_after, and sharding considerations, with Java code examples and execution plan verification.

Why LIMIT offset Is Slow

When an order table grows to tens of millions of rows, a query like SELECT * FROM t_order ORDER BY id LIMIT 999990, 10 can degrade from milliseconds to seconds. MySQL does not jump directly to the offset; it scans offset + size rows, discards the first offset rows, and returns the last size rows. If the sort uses a secondary index and the query selects *, each scanned index record triggers a primary-key lookup (回表) to the clustered index. For page 1,000,000 this means scanning ~1,000,010 index entries and performing ~1,000,010 random I/O lookups, then throwing away 99.99% of the data. The author summarizes the core cost as "massive useless scans + massive useless lookups".

Key insight: Optimization has only two paths: make the useless work cheaper, or eliminate it entirely.

Deferred Join (Stop‑Gap for Jump‑Page UIs)

When random page jumps are required (e.g., admin panels), a deferred join reduces lookups to the current page size. The subquery selects only the primary key using a covering index, avoiding lookups during the scan; the outer query joins back to fetch full rows for the 10 IDs.

SELECT o.* FROM t_order o INNER JOIN (SELECT id FROM t_order ORDER BY id LIMIT 999990, 10) AS t ON o.id = t.id ORDER BY o.id;

For time‑based sorting, the covering index must include the sort columns and the primary key, e.g., KEY idx_created_id (create_time, id). The outer ORDER BY must be repeated because the join does not guarantee order.

Benchmark on a 15 M‑row table: original query ~4.3 s, deferred join ~84 ms, cursor pagination ~1.2 ms. On a 10 M‑row SSD setup at page 50,000: original ~8.6 s, deferred join ~620 ms, cursor ~2 ms. These numbers illustrate direction only; actual results depend on index width, cache, disk, filters, and data distribution.

MyBatis Two‑Step Implementation

@Mapper public interface OrderMapper { @Select("SELECT id FROM t_order WHERE shop_id = #{shopId} AND create_time >= #{start} ORDER BY id DESC LIMIT #{offset}, #{size}") List<Long> selectIdsByPage(@Param("shopId") Long shopId, @Param("start") LocalDateTime start, @Param("offset") int offset, @Param("size") int size); @Select("<script>SELECT * FROM t_order WHERE id IN <foreach collection='ids' item='id' open='(' separator=',' close=')'>#{id}</foreach> ORDER BY id DESC</script>") List<Order> selectByIds(@Param("ids") List<Long> ids); }

Always verify with EXPLAIN that the subquery shows Using index (covering index). Do not assume the optimizer behaves as expected just because the SQL looks optimized.

Cursor Pagination (Primary Solution for Sequential Access)

For infinite scroll, order feeds, or sequential exports, cursor pagination eliminates the offset entirely. Remember the last seen primary key (or composite sort key) and query WHERE id > #{lastId} ORDER BY id LIMIT 10 (ascending) or WHERE id < #{lastId} ORDER BY id DESC LIMIT 10 (descending). The B+ tree locates the cursor in O(log n) and reads only the requested page. Gaps from deleted IDs do not affect correctness because the comparison is on values, not physical continuity.

Key insight: Page numbers ask "how many before?" — requiring a recount. Cursors ask "continue from here" — enabling direct positioning.

Java Implementation

public List<Order> cursorQuery(Long lastId, int size) { String sql = "SELECT id, order_no, amount, create_time FROM orders WHERE id > ? ORDER BY id ASC LIMIT ?"; return jdbcTemplate.query(sql, new Object[]{lastId, size}, (rs, rowNum) -> mapOrder(rs)); } @GetMapping("/orders") public PageResult<Order> list(@RequestParam(required = false) Long lastId, @RequestParam(defaultValue = "10") int size) { Long cursor = lastId == null ? 0L : lastId; List<Order> orders = orderService.cursorQuery(cursor, size); return PageResult.<Order>builder().records(orders).nextCursor(orders.isEmpty() ? null : orders.get(orders.size() - 1).getId()).hasMore(orders.size() == size).build(); }

To reliably detect hasMore, fetch size + 1 rows; if the result exceeds size, trim the extra row and set hasMore = true. This avoids the edge case where the last page exactly matches the page size. Also drop real‑time COUNT(*) — use cached totals, approximate counts, or simply show "load more". Enforce a maximum size (e.g., 100) to prevent abuse.

Composite Cursors for Time‑Based Sorting

When sorting by create_time DESC, multiple orders can share the same timestamp. A single create_time cursor would skip peers with the same time. The solution is a composite key (create_time, id) as a tie‑breaker, ensuring a unique, stable sort order.

SELECT * FROM t_order WHERE (create_time, id) < (#{lastCreateTime}, #{lastId}) ORDER BY create_time DESC, id DESC LIMIT 10;

MySQL 8.0 supports row‑value comparison directly. For older versions or to guide the optimizer, expand to:

WHERE status = 'PAID' AND (create_time < #{lastCreateTime} OR (create_time = #{lastCreateTime} AND id < #{lastId})) ORDER BY create_time DESC, id DESC LIMIT #{limit};

An alternative range‑start form uses create_time <= #{lastTime} plus the tie‑breaker. Warning: Top‑level OR can sometimes prevent range scans; always validate with EXPLAIN on real data.

Index Alignment

The index column order must match the query: equality filters first, then range/sort columns. Examples:

Query: ORDER BY create_time DESC, id DESC → Index: (create_time, id) Query: WHERE status = ? ORDER BY create_time, id → Index: (status, create_time, id) Query: WHERE user_id = ? ORDER BY create_time, id → Index: (user_id, create_time, id) Query: WHERE shop_id = ? AND create_time >= ? ORDER BY id → Index: combine filter columns, e.g., (shop_id, create_time, id), and verify with EXPLAIN MySQL 8.0 allows explicit DESC in index definitions; 5.7 relies on backward index scans for uniform DESC but struggles with mixed ASC/DESC.

Secure, Versioned Cursor Tokens

Expose cursors as opaque Base64‑encoded tokens containing a version byte, timestamp, and ID. This allows future schema changes (versioning) and prevents tampering. For sensitive contexts, append an HMAC‑SHA256 signature (truncated to 8 bytes) and verify with constant‑time comparison ( MessageDigest.isEqual). Store signing keys in a secrets manager, not in code.

public record OrderCursor(LocalDateTime ct, long id) { public static final OrderCursor FIRST = new OrderCursor(LocalDateTime.of(9999,12,31,23,59,59), Long.MAX_VALUE); public static OrderCursor decode(String token) { if (token == null || token.isBlank()) return FIRST; ByteBuffer b = ByteBuffer.wrap(Base64.getUrlDecoder().decode(token)); if (b.get() != 1) throw new IllegalArgumentException("cursor version mismatch"); return new OrderCursor(LocalDateTime.ofEpochSecond(b.getLong(), 0, ZoneOffset.ofHours(8)), b.getLong()); } public String encode() { return Base64.getUrlEncoder().withoutPadding().encodeToString(ByteBuffer.allocate(17).put((byte)1).putLong(ct.toEpochSecond(ZoneOffset.ofHours(8))).putLong(id).array()); } }

Consistency During Pagination

Cursor pagination avoids offset drift but does not guarantee a stable snapshot if sort/filter columns change, rows are deleted, or new rows insert within the scanned range. Strategies:

Regular C‑end list: Unique stable composite cursor; accept eventual consistency

Sort/filter columns change: Anchor to immutable monotonic ID; add snapshot version + deduplication

Financial reconciliation: Fixed query conditions + time boundaries; use data snapshot

ES deep paging: search_after + PIT (Point In Time) for fixed search snapshot

Strict jump‑page required: Materialized page anchors or snapshots; avoid real‑time offset drift

"Unique sort key" stabilizes page boundaries; "snapshot" stabilizes the dataset. They address different problems.

Product‑Level Guardrails

Before engineering a solution, ask: does the user need to jump pages or find a specific record? Often "jump to page N" masks missing filters. Product constraints:

Only prev/next/load‑more; disable arbitrary deep jumps.

Cap maximum page depth (e.g., 100 or 500 pages).

Reject offsets beyond threshold; prompt to narrow filters.

Force/guide time, shop, user, status filters.

Replace "page 100,000" with "before 2025‑01".

Cache hot‑page ID lists in Redis.

Separate export from online queries.

If exact jump‑page is unavoidable, fallbacks include deferred join + covering index, page‑anchor tables (materialize every 1,000 pages), binary‑search estimation, migrating complex search to ES, or pre‑computed page caches.

Principle: Technical solutions provide safety nets; product constraints keep most deep pagination out of the database.

Streaming Million‑Row Exports

Do not paginate exports with increasing offsets. Instead, slice by time windows and stream each slice with a cursor. Use MySQL Connector/J streaming ResultSet ( setFetchSize(Integer.MIN_VALUE) with TYPE_FORWARD_ONLY, CONCUR_READ_ONLY) or MyBatis @Options(fetchSize = Integer.MIN_VALUE) returning Cursor<Order>. Note: fetchSize = 500 is a batch‑fetch hint; true row‑by‑row streaming requires Integer.MIN_VALUE.

Full pipeline: submit task → return taskId → background cursor batches → stream write Excel (SXSSFWorkbook or EasyExcel streaming) → upload to OSS → notify download. For huge datasets, parallelize by primary‑key ranges ( id BETWEEN ? AND ?) with a fixed thread pool, but apply rate limiting to avoid overwhelming the DB. Run exports on replicas with read‑only accounts, SQL timeouts, circuit breakers, and rate limits.

Elasticsearch: search_after + PIT

When multi‑condition search and deep paging exceed MySQL capabilities, sync data to ES via binlog/Canal/MQ. ES from + size has the same offset problem and is capped at max_result_window=10000. Use search_after with a unique sort tie‑breaker (e.g., _id) and PIT (Point In Time) to freeze the search snapshot across pages.

searchSourceBuilder.size(100).sort("create_time", SortOrder.DESC).sort("_id", SortOrder.ASC); if (lastSortValues != null) searchSourceBuilder.searchAfter(lastSortValues);

Sharding Amplifies Deep Pagination

With 4 shards, a global LIMIT 1000000, 10 may force each shard to scan LIMIT 0, 1000010, merging ~4 M rows over the network. Practical rules:

C‑end "my orders" must include shard key ( user_id) to route to a single shard, then cursor.

Cursors must carry shard key or routing context.

Avoid unconditional broadcast to all shards.

Cross‑shard multi‑condition queries → global index or ES.

Product: forbid unconstrained global deep jumps.

If global exact jump is mandatory, a two‑phase query can reduce cross‑shard scans: estimate local offsets, find global minimum sort value, re‑query each shard within a narrowed range, then merge in memory. Complexity makes this a last resort.

Decision Matrix

Raw LIMIT offset, size — Random jump: Yes; Scan growth: O(offset); Refactor cost: None; Best for: Small tables, shallow paging, ad‑hoc

Deferred join + covering index — Random jump: Yes; Scan growth: Still O(offset), fewer lookups; Refactor cost: Low (SQL only); Best for: Legacy admin, must keep page numbers

Single‑key cursor — Random jump: No; Scan growth: Seek + page only; Refactor cost: Medium (FE/BE); Best for: Lists sorted by unique ID

Composite cursor — Random jump: No; Scan growth: Seek + page only; Refactor cost: Medium; Best for: Time‑sorted lists with duplicate timestamps

Page‑anchor table — Random jump: Yes; Scan growth: Scan from nearest anchor; Refactor cost: High; Best for: Rare precise deep‑jump needs

ES search_after + PIT — Random jump: No direct page; Scan growth: Stable by sort value; Refactor cost: High; Best for: Multi‑condition huge search, snapshot paging

Limit depth + forced filters — Random jump: Limited; Scan growth: Controlled at source; Refactor cost: Low‑Medium; Best for: Most admin and C‑end products

Async streaming export — Random jump: N/A; Scan growth: Batched/streaming; Refactor cost: Medium; Best for: Reconciliation, reports, million‑row exports

Author's Recommended Rollout Order

Immediate pain: apply deferred join to cut lookups.

Convert sequential lists to unique, stable cursor pagination.

Use size + 1 for hasMore; drop real‑time COUNT(*).

Validate indexes, covering scans, and sort with EXPLAIN — no guessing.

Cap max page depth and size; steer users to filters.

Move exports to async, batched, or streaming; run on replicas.

Migrate complex search to ES; archive cold data to ClickHouse/TiDB; shard only when single‑table write/read hits ceiling.

Interview‑ready summary: Sequential paging uses cursors so the DB continues from the last position; mandatory jump‑page uses covering index + deferred join to push lookups to the current page; at scale combine depth limits, filters, async export, ES, and shard routing. Always append a unique ID to the sort key and verify with EXPLAIN .
About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

Javaperformance optimizationElasticsearchshardingMySQLMyBatisdeep-paginationpaginationSQL-optimizationcovering-indexcursor-paginationdeferred-join

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion