agentleFS
polardbpolardb/polardbx-skills/skills/polardbx-pagination/SKILL.md

polardbx-pagination

Skill8 starsChanged 30 days agoApache-2.0View on GitHub

Efficient pagination and large table traversal for PolarDB-X 2.0 Enterprise Edition. Recommends Keyset pagination (cursor pagination) over LIMIT M,N for deep pagination scenarios, provides per-shard traversal for extreme cases, includes index requirements and complete Java code examples. Use when implementing pagination queries, traversing large tables, exporting data in batches, or optimizing slow LIMIT M,N queries on PolarDB-X. Triggers: "分页查询", "deep pagination", "Keyset pagination", "大表遍历", "数据导出", "LIMIT优化", "分页性能", "cursor pagination", "游标分页", "翻页慢", "深翻页", "pagination query", "batch traversal", "LIMIT M N slow", "efficient paging"

The file

We split this skill into the rules it gives an agent

3 rules. About 0 are common, 1 is distinctive, and 2 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈1

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 2

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Verify cursor correctness and consistency: use immutable keys that are globally unique as a tuple.

    line 34
  2. Very specific:

    Use an immutable, globally unique (sort_column, id) tuple as the cursor.

    line 58
  3. Very specific:

    Choose autocommit by consistency requirements: use autocommit=true for best-effort live browsing.

    line 125

≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

PolarDB-X Efficient Pagination — Keyset Pagination & Large Table Traversal

Implement efficient pagination for PolarDB-X 2.0 Enterprise Edition (AUTO mode) that maintains constant performance regardless of page depth. Covers Keyset pagination strategies, per-shard traversal, index requirements, and production-ready Java code.

Scope: PolarDB-X 2.0 Enterprise Edition + AUTO mode database only.

Why LIMIT M, N Fails for Deep Pagination

  • Standalone DB cost: O(M+N) — must scan M rows before returning N rows.
  • Distributed DB cost: O(M+N) × number of shards — each shard returns M+N rows to CN for merge-sort.
  • Result: Performance degrades linearly as page number increases; unacceptable for large tables.

For small data volumes with shallow pagination (< 1000 offset), LIMIT M, N is acceptable.

Core Workflow

  1. Determine the pagination scenario:
    • Does the table use New Sequence (AUTO mode default)? → Scenario A
    • Is the sort column potentially non-unique (time column, group sequence ID)? → Scenario B
    • Are there extreme stability requirements with many shards? → Per-shard traversal
  2. Select the pagination strategy (see Quick Reference below).
  3. Verify cursor correctness and consistency: use immutable keys that are globally unique as a tuple; handle nullable sort keys explicitly. Decide whether pages are best-effort live reads or an exact snapshot/export. Independent autocommit pages can miss late commits or updates behind the cursor.
  4. Verify index exists for the sort columns (critical for performance).
  5. Generate code with JDBC settings matching the chosen consistency model.

Pagination Strategies Quick Reference

Scenario A: New Sequence ID (AUTO mode default)

A globally unique ID defines a deterministic cursor order, but sequence allocation order does not imply commit-time order:

-- First batch
SELECT * FROM t1 ORDER BY id LIMIT 1000;

-- Subsequent batches (record last_id from previous batch)
SELECT * FROM t1 WHERE id > :last_id ORDER BY id LIMIT 1000;

Cost: O(N) constant, regardless of page depth.

Scenario B: Sort Column May Have Duplicates (time columns, etc.)

Use an immutable, globally unique (sort_column, id) tuple as the cursor. The example assumes both fields are non-NULL; otherwise explicitly paginate the NULL segment or use an equivalent non-NULL sort key:

-- First batch
SELECT * FROM t1 ORDER BY gmt_create, id LIMIT 1000;

-- Subsequent batches (record last_gmt_create and last_id)
SELECT * FROM t1
WHERE (gmt_create, id) > (:last_gmt_create, :last_id)
ORDER BY gmt_create, id LIMIT 1000;

PolarDB-X supports tuple comparison (col1, col2) > (?, ?) and can leverage composite indexes.

Per-Shard Traversal (Advanced)

For extreme scenarios (many shards, relaxed ordering):

-- 1. Get topology
SHOW TOPOLOGY FROM t1;

-- 2. Paginate within each shard using HINT
/*+TDDL:NODE('partition_name')*/
SELECT * FROM t1 WHERE (gmt_create, id) > (?, ?)
ORDER BY gmt_create, id LIMIT 1000;

Index Requirements

Sort MethodRequired Index
ORDER BY idPrimary key (usually exists)
ORDER BY gmt_create, id(gmt_create, id) composite index
ORDER BY c1, gmt_create, id (with WHERE c1 = ?)(c1, gmt_create, id) composite index
-- Create composite index for pagination
ALTER TABLE t1 ADD INDEX idx_page (gmt_create, id);

Method Comparison

MethodPerformanceApplicable ScenariosNotes
LIMIT M, NO(M+N), degradingShallow pagination, small dataEven worse in distributed systems
Keyset (id)O(N), constantTraverse in ID orderRequires globally unique ID; not commit-time order
Keyset (sort_col, id)O(N), constantSort columns with possible duplicatesRequires composite index
Per-shard traversalO(N), constantMany shards, relaxed orderingRequires SHOW TOPOLOGY + HINT
Batch ToolInternally optimizedData exportDedicated tool

Java JDBC Settings

ParameterValueReason
netTimeoutForStreamingResults0Avoid streaming read timeouts
socketTimeoutAs needed (ms)Avoid long queries being disconnected
setFetchSizeInteger.MIN_VALUEEnable streaming reads (avoid OOM)
autocommittrue for best-effort live browsingAvoid long transactions; pages do not share a snapshot

For exact exports, define a stable snapshot or quiesce writes; if using change capture, reconcile changes against the chosen snapshot boundary. A maximum-ID watermark alone does not catch late commits with smaller IDs. Do not promise omission-free traversal from independent page reads.

Best Practices

  1. Never use LIMIT M,N for deep pagination on large tables — cost grows linearly.
  2. Always create composite indexes matching your ORDER BY columns.
  3. Use tuple comparison (col, id) > (?, ?) for non-unique sort columns — PolarDB-X supports this natively.
  4. Choose autocommit by consistency requirements: use autocommit=true for best-effort live browsing; for exact exports, use an appropriate snapshot/export strategy and assess long-transaction costs.
  5. Use streaming reads (fetchSize = Integer.MIN_VALUE) to avoid loading entire result sets into memory.
  6. Consider Batch Tool for pure data export scenarios — it has built-in PolarDB-X optimizations.

Reference

ReferenceDescription
references/pagination-best-practice.mdComplete pagination guide: all scenarios, per-shard traversal details, full Java code example, Batch Tool, FAQ

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.