Write, review, and adapt SQL for PolarDB-X 2.0 Enterprise Edition (Distributed Edition) AUTO mode databases, avoiding the "runs on MySQL but fails on PolarDB-X" problem.
Architecture: PolarDB-X 2.0 Enterprise Edition (CN compute nodes + DN storage nodes + GMS metadata service + CDC log nodes) + AUTO mode database
Scope:
Not applicable to:
Key difference between AUTO mode and DRDS mode: AUTO mode uses MySQL-compatible PARTITION BY syntax to define partitions, while DRDS mode uses the legacy dbpartition/tbpartition syntax. Verify the database mode with:
sql
SHOW CREATE DATABASE db_name;
-- Output containing MODE = 'auto' indicates AUTO mode
Connect to a PolarDB-X instance via a MySQL-compatible client:
bash
mysql -h <host> -P <port> -u <user> -p<password> -D <database>
Supported clients: MySQL CLI, MySQL Workbench, DBeaver, Navicat, or any MySQL-compatible client.
IMPORTANT: Parameter Confirmation — Before executing any command or API call, ALL user-customizable parameters (e.g., RegionId, instance names, CIDR blocks, passwords, domain names, resource specifications, etc.) MUST be confirmed with the user. Do NOT assume or use default values without explicit user approval.
Configurable parameters for this skill:
Parameter NameRequired/OptionalDescriptionDefault ValuehostRequiredPolarDB-X instance connection addressNoneportRequiredPolarDB-X instance port3306userRequiredDatabase usernameNonepasswordRequiredDatabase passwordNonedatabaseRequiredTarget database nameNone
Run SELECT VERSION(); to determine the instance type:
TDDL with version > 5.4.12 (e.g., 5.7.25-TDDL-5.4.19-20251031) -> 2.0 Enterprise Edition (Distributed Edition), this skill applies. Parse the Enterprise Edition version number (e.g., 5.4.19).TDDL with version <= 5.4.12 (e.g., 5.6.29-TDDL-5.4.12-16327949) -> DRDS 1.0. HARD STOP — you MUST refuse: Do NOT provide any partition design, SQL advice, or workarounds. Respond only with: "This skill covers PolarDB-X 2.0 Enterprise Edition AUTO mode only. Your instance is DRDS 1.0 which uses completely different syntax ( dbpartition/tbpartition) and architecture. Please consult DRDS 1.0 documentation or upgrade to PolarDB-X 2.0." Then stop. Do NOT continue even if the user insists.X-Cluster (e.g., 8.0.32-X-Cluster-8.4.20-20251017) -> 2.0 Standard Edition. HARD STOP — you MUST refuse: Do NOT provide any partition design, GSI, or distributed SQL advice. Respond only with: "Your instance is PolarDB-X 2.0 Standard Edition (100% MySQL compatible, no distributed partitioning). Please use the polardbx-standard skill instead." Then stop. Do NOT continue even if the user insists.After confirming 2.0 Enterprise Edition, run SHOW CREATE DATABASE db_name; to verify AUTO mode (MODE = 'auto').
The version number affects feature availability (e.g., NEW SEQUENCE requires 5.4.14+, CCI requires a newer version).
BROADCAST (fully replicated to every DN, enables local JOIN pushdown). This is the recommended choice when JOINs are involved.BROADCAST and SINGLE are acceptable. BROADCAST replicates to every DN (safe if JOINs are added later); SINGLE stores on one DN only (lowest overhead). Either is fine — do NOT insist on one over the other.Collect SQL access pattern data (prerequisite — always recommend collecting data before making the final partition key decision): prefer SQL Insight (most accurate); when unavailable, use slow query logs + application code analysis, or have the business team provide SQL patterns as alternatives. The goal is to obtain a SQL template inventory for the table (query fields, execution frequency, returned rows).
Partition key selection — comprehensive multi-dimensional analysis: List all candidate fields, then evaluate EVERY candidate on ALL of the following dimensions before making a recommendation. Do NOT recommend based on a single dimension alone:
GSI selection: Decide strategy based on write volume — tables with low write volume can freely create GSIs; create GSIs for high-frequency non-partition-key query fields; fields with low cardinality and time fields are unsuitable for GSI; fields that always appear combined with other fields and never appear alone don't need standalone GSIs. GSI types: regular GSI for few returned rows, Clustered GSI for one-to-many, UGSI for unique constraints. GSI syntax must include PARTITION BY KEY(...) PARTITIONS N — see gsi.md for full syntax.
Partition algorithm: ~90% of workloads use single-level HASH/KEY; order-type multi-dimensional queries use CO_HASH; time-based data cleanup uses HASH+RANGE; multi-tenant uses LIST+HASH. For single column, HASH and KEY are equivalent.
Partition count: 256 suits the vast majority of workloads; should be several times the number of DN nodes; keep single partition under 100 million rows.
Migration workflow (three-step method for single table to partitioned table): (1) First convert to a partitioned table with 1 partition (preserving uniqueness) -> (2) Create required GSI/UGSI -> (3) Change to the target partition count. See partition-design-best-practice.md for details.
KEY or HASH partitioning instead of MySQL's AUTO_INCREMENT primary key write hotspot.EXPLAIN to view the logical execution plan.EXPLAIN EXECUTE to view the physical execution plan pushed down to DN.EXPLAIN SHARDING to view shard scan details and check for full-shard scans.EXPLAIN ANALYZE to actually execute and collect runtime statistics.Three table types: Single table ( SINGLE), Broadcast table ( BROADCAST), Partitioned table (default); choose based on data volume and access patterns.
Partitioned tables: Support KEY/HASH/RANGE/LIST/RANGE COLUMNS/LIST COLUMNS/CO_HASH + secondary partitions (49 combinations).
Primary keys and unique keys: Classified as Global (globally unique) or Local (unique within partition); single/broadcast/auto-partitioned tables are always Global; manual partitioned tables are Global when partition columns are a subset of PK/UK columns, otherwise Local (risk of data duplication and DDL failure). Key principle: prefer choosing partition keys FROM existing PK/UK columns to naturally guarantee global uniqueness — do NOT modify the user's existing primary key definition to add partition columns.
Global Secondary Index GSI: Solves full-shard scan issues for non-partition-key queries, supports GSI / UGSI / Clustered GSI types. CRITICAL: GSI must specify its own PARTITION BY clause — it is an independently partitioned table, not a regular MySQL index. Correct syntax: sql
-- ✅ Correct: GSI with PARTITION BY clause
GLOBAL INDEX g_i_seller(seller_id) PARTITION BY KEY(seller_id) PARTITIONS 16
CLUSTERED INDEX cg_i_buyer(buyer_id) PARTITION BY KEY(buyer_id) PARTITIONS 16
-- ❌ Wrong: Missing PARTITION BY (this is NOT MySQL INDEX syntax)
GLOBAL INDEX gsi_seller(seller_id)
Classic partition design — order table: Candidates are order_id (PK) and buyer_id. Comprehensive analysis: order_id has the highest cardinality (unique per row), zero hotspot risk, PK status, and semantically high query frequency (order detail/status/payment lookups); buyer_id has high buyer-dimension query ratio but potential distribution skew (some buyers generate far more orders). Conclusion: order_id as partition key + Clustered GSI on buyer_id.
Clustered Columnar Index CCI: Row-column hybrid storage, accelerates OLAP analytical queries via CLUSTERED COLUMNAR INDEX.
Sequence: Globally unique sequence, default type is NEW SEQUENCE (5.4.14+), distributed alternative to AUTO_INCREMENT.
Distributed transactions: Based on TSO global clock + MVCC + 2PC, strong consistency by default; single-shard transactions automatically optimized to local transactions.
Table groups: Tables with the same partition rules bound to the same table group, ensuring JOIN computation pushdown to avoid cross-shard data shuffling.
TTL tables: Automatic expiration and cleanup of cold data based on time columns, can work with CCI for hot/cold data separation.
Unsupported MySQL features: Stored procedures/triggers/EVENTs/SPATIAL/GEOMETRY/LOAD XML/HANDLER, etc.
STRAIGHT_JOIN / NATURAL JOIN not supported: Use standard JOIN syntax instead.
:= assignment operator not supported: Move logic to the application layer.
Subqueries not supported in HAVING/JOIN ON clauses: Rewrite subqueries as JOINs or CTEs.
INSPECT INDEX to periodically clean up redundant GSIs. Every GSI must have its own PARTITION BY KEY(...) PARTITIONS N clause; never write bare GLOBAL INDEX idx(col) without PARTITION BY.:=, etc.EXPLAIN SHARDING and EXPLAIN ANALYZE.LIMIT M, N deep pagination (cost O(M+N), even larger in distributed systems); record the sort value of the last row in each batch as the WHERE condition for the next batch; when sort columns may have duplicates, use (sort_column, id) tuple comparison; ensure appropriate composite indexes on sort columns.ALTER TABLE ... MODIFY TTL SET syntax (with multiple parameters like TTL_EXPR, TTL_PART_INTERVAL, ARCHIVE_TYPE, ARCHIVE_TABLE_PRE_ALLOCATE, etc.) to configure automatic partition pre-creation. This syntax is NOT standard SQL and cannot be guessed — you MUST read references/auto-add-range-parts.md for the exact SQL syntax before generating any auto-add partition configuration. Requires version 5.4.20+.ReferenceDescriptionreferences/create-table.mdCREATE TABLE syntax, table types (single/broadcast/partitioned), partition strategies, secondary partitions, partition managementreferences/partition-design-best-practice.mdPartition design best practices: partition key/GSI/algorithm/count selection, three-step migration, complete examplesreferences/primary-key-unique-key.mdPrimary key and unique key Global/Local classification, rules, risks, and recommendationsreferences/gsi.mdGlobal Secondary Index GSI/UGSI/Clustered GSI creation, querying, and limitationsreferences/cci.mdClustered Columnar Index CCI creation, usage, and applicable scenariosreferences/sequence.mdSequence types (NEW/GROUP/SIMPLE/TIME), creation and usagereferences/transactions.mdDistributed transaction model, isolation levels, and considerationsreferences/mysql-compatibility-notes.mdMySQL vs PolarDB-X compatibility differences and development limitationsreferences/explain.mdEXPLAIN command variants and execution plan diagnosticsreferences/ttl-table.mdTTL table definition, cold data archiving, and cleanup schedulingreferences/online-ddl.mdOnline DDL assessment, lock-free execution strategy, long transaction checks, DMS lock-free changesreferences/pagination-best-practice.mdEfficient pagination: Keyset pagination, per-shard traversal, index requirements, Java examplesreferences/auto-add-range-parts.mdRange partition auto-add: TTL-based partition pre-creation, first/second level configuration, management commandsreferences/cli-installation-guide.mdAlibaba Cloud CLI installation guide