Todos os produtos
Search
Central de documentação

PolarDB:ALTER TABLE (modo AUTO)

Última atualização: Jun 28, 2026

Use ALTER TABLE para modificar o esquema de uma tabela existente em um banco de dados no modo AUTO. As alterações compatíveis incluem adicionar ou remover colunas, criar ou remover índices, renomear índices e modificar tipos de colunas.

Esta sintaxe se aplica apenas a bancos de dados no modo AUTO.

Operações compatíveis

A tabela a seguir lista as operações alter_specification compatíveis com o modo AUTO. Para modificar um índice secundário global (GSI), use alter_specification apenas uma vez por instrução ALTER TABLE.

Operação

Descrição

Palavra-chave de sintaxe

Adicionar uma coluna

Adiciona uma nova coluna à tabela

ADD COLUMN

Modificar uma coluna

Altera o tipo ou o comprimento de uma coluna

MODIFY COLUMN

Criar um índice

Adiciona um índice secundário local

ADD INDEX

Remover um índice

Remove um índice ou GSI e sua tabela de índice associada

DROP INDEX

Renomear um índice

Renomeia um índice secundário local

RENAME INDEX

Adicionar um GSI

Adiciona um índice secundário global após a criação da tabela

ADD GLOBAL INDEX

Diferenças em relação ao MySQL

O modo AUTO do PolarDB-X é compatível com a sintaxe padrão do MySQL ALTER TABLE, com as seguintes diferenças:

  • Índices secundários globais: O PolarDB-X introduz a palavra-chave GLOBAL para ADD GLOBAL INDEX e ADD UNIQUE GLOBAL INDEX. O MySQL padrão não possui equivalente.

  • Alterações na chave de shard: Em instâncias anteriores à versão 5.4.17-16835173, o comando ALTER TABLE não pode alterar chaves de shard.

  • Renomeação de GSI: Por padrão, não é possível renomear índices secundários globais.

  • Única alter_specification para GSI: Cada instrução ALTER TABLE pode incluir apenas uma alter_specification ao modificar um GSI.

Sintaxe

ALTER TABLE tbl_name
    [alter_specification [, alter_specification] ...]
  [partition_options]
  [local_partition_alter_options]

Exemplos

Adicionar uma coluna

ALTER TABLE user_log
    ADD COLUMN idcard VARCHAR(30);

Criar um índice

ALTER TABLE user_log
    ADD INDEX idcard_idx (idcard);

Remover um índice

ALTER TABLE user_log
    DROP INDEX idcard_idx;

Rename an index

ALTER TABLE user_log
    RENAME INDEX `idcard_idx` TO `idcard_idx_new`;

Modify a column

-- Extend the idcard column from 30 to 40 characters.
ALTER TABLE user_log
    MODIFY COLUMN idcard VARCHAR(40);

Índices secundários globais

O PolarDB-X oferece suporte a índices secundários globais (GSIs). Para obter uma visão geral, consulte GSI.

Modifique colunas em tabelas com GSIs da mesma forma que em tabelas comuns. Existem limites aplicáveis — consulte Como usar índices secundários globais.

Adicionar ou remover um GSI

Sintaxe

ALTER TABLE tbl_name
    alter_specification   -- Use alter_specification only once per statement when modifying a GSI.

alter_specification:
  | ADD GLOBAL {INDEX|KEY} index_name   -- Explicitly specify the GSI name.
      [index_type] (index_sharding_col_name,...)
      global_secondary_index_option
      [index_option] ...
  | ADD [CONSTRAINT [symbol]] UNIQUE GLOBAL
      [INDEX|KEY] index_name            -- Explicitly specify the GSI name.
      [index_type] (index_sharding_col_name,...)
      global_secondary_index_option
      [index_option] ...
  | DROP {INDEX|KEY} index_name
  | RENAME {INDEX|KEY} old_index_name TO new_index_name

-- Applies only to global secondary indexes. See CREATE TABLE (DRDS mode) for full definitions.
global_secondary_index_option:
    [COVERING (col_name,...)]   -- Covering index
    partition_options           -- Must include columns from index_sharding_col_name.

-- Specify a partitioning method for the index table.
partition_options:
    PARTITION BY
          HASH({column_name | partition_func(column_name)})
        | KEY(column_list)
        | RANGE{({column_name | partition_func(column_name)})
        | RANGE COLUMNS(column_list)}
        | LIST{({column_name | partition_func(column_name)})
        | LIST COLUMNS(column_list)} }
    partition_list_spec

-- Supported partition functions.
partition_func:
    YEAR
  | TO_DAYS
  | TO_SECOND
  | UNIX_TIMESTAMP
  | MONTH

partition_list_spec:
    hash_partition_list
  | range_partition_list
  | list_partition_list

-- Hash and KEY partitioning: specify the number of partitions.
hash_partition_list:
    PARTITIONS partition_count

-- Range partitioning: specify value boundaries.
range_partition_list:
    range_partition [, range_partition ...]

range_partition:
    PARTITION partition_name VALUES LESS THAN {(expr | value_list)} [partition_spec_options]

-- List partitioning: specify value sets.
list_partition_list:
    list_partition [, list_partition ...]

list_partition:
    PARTITION partition_name VALUES IN (value_list) [partition_spec_options]

partition_spec_options:
        [[STORAGE] ENGINE [=] engine_name]
        [COMMENT [=] 'string' ]

-- MySQL DDL syntax.
index_sharding_col_name:
    col_name [(length)] [ASC | DESC]

index_option:
    KEY_BLOCK_SIZE [=] value
  | index_type
  | WITH PARSER parser_name
  | COMMENT 'string'

index_type:
    USING {BTREE | HASH}

O comando ADD GLOBAL INDEX introduz a palavra-chave GLOBAL, que identifica o índice como um índice secundário global. Use ALTER TABLE DROP INDEX e ALTER TABLE RENAME INDEX para gerenciar GSIs existentes, respeitando os limites descritos em Como usar índices secundários globais.

Para a sintaxe completa das cláusulas usadas para definir índices secundários globais, consulte CREATE TABLE (modo DRDS).

Exemplo: adicionar um GSI após a criação da tabela

O exemplo a seguir cria uma tabela e adiciona um GSI na coluna buyer_id.

-- Create the base table, partitioned by order_id.
CREATE TABLE t_order (
  `id` bigint(11) NOT NULL AUTO_INCREMENT,
  `order_id` varchar(20) DEFAULT NULL,
  `buyer_id` varchar(20) DEFAULT NULL,
  `seller_id` varchar(20) DEFAULT NULL,
  `order_snapshot` longtext DEFAULT NULL,
  `order_detail` longtext DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `l_i_order` (`order_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
PARTITION BY KEY(`order_id`)
PARTITIONS 4;

-- Add a GSI on buyer_id, with order_snapshot as a covering column.
ALTER TABLE t_order
    ADD UNIQUE GLOBAL INDEX `g_i_buyer` (`buyer_id`)
    COVERING (`order_snapshot`)
    PARTITION BY KEY(`buyer_id`) PARTITIONS 4;

Após esta instrução:

  • Tabela base (t_order): fragmentada por order_id usando o algoritmo de hash.

  • Tabela de índice (g_i_buyer): fragmentada por buyer_id usando o algoritmo de hash. A coluna order_snapshot está incluída como coluna de cobertura.

Execute SHOW INDEX para confirmar os índices em um shard da tabela base:

SHOW INDEX FROM t_order;
+--------------------+------------+-----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table              | Non_unique | Key_name  | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+--------------------+------------+-----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| t_order_syes_00000 |          0 | PRIMARY   |            1 | id          | A         |           0 |     NULL | NULL   |      | BTREE      |         |               |
| t_order_syes_00000 |          1 | l_i_order |            1 | order_id    | A         |           0 |     NULL | NULL   | YES  | BTREE      |         |               |
+--------------------+------------+-----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
2 rows in set (0.05 sec)

As informações do índice incluem o índice secundário local na chave de shard order_id e os índices secundários globais nas colunas buyer_id, id, order_id e order_snapshot. Para mais informações, consulte SHOW INDEX.

Execute SHOW GLOBAL INDEX para consultar todos os GSIs:

SHOW GLOBAL INDEX;
+--------+---------+------------+-----------------+-------------+------------------------------+------------+------------------+---------------------+--------------------+------------------+---------------------+--------------------+--------+
| SCHEMA | TABLE   | NON_UNIQUE | KEY_NAME        | INDEX_NAMES | COVERING_NAMES               | INDEX_TYPE | DB_PARTITION_KEY | DB_PARTITION_POLICY | DB_PARTITION_COUNT | TB_PARTITION_KEY | TB_PARTITION_POLICY | TB_PARTITION_COUNT | STATUS |
+--------+---------+------------+-----------------+-------------+------------------------------+------------+------------------+---------------------+--------------------+------------------+---------------------+--------------------+--------+
| d1     | t_order | 0          | g_i_buyer_$c1a0 | buyer_id    | id, order_id, order_snapshot | NULL       |                  |                     | NULL               |                  |                     | NULL               | PUBLIC |
+--------+---------+------------+-----------------+-------------+------------------------------+------------+------------------+---------------------+--------------------+------------------+---------------------+--------------------+--------+
1 row in set (0.04 sec)

A coluna COVERING_NAMES exibe todas as colunas de cobertura: id e order_id são incluídas automaticamente (chave primária e chave de shard da tabela base), enquanto order_snapshot é a coluna de cobertura especificada explicitamente.

Para inspecionar o esquema da tabela de índice:

SHOW CREATE TABLE g_i_buyer;
+-----------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| TABLE           | CREATE TABLE                                                                                                                                                                                                                                                                                                                                                  |
+-----------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| g_i_buyer_$c1a0 | CREATE TABLE `g_i_buyer_$c1a0` (
    `id` bigint(11) NOT NULL,
    `order_id` varchar(20) DEFAULT NULL,
    `buyer_id` varchar(20) DEFAULT NULL,
    `order_snapshot` longtext,
    UNIQUE KEY `auto_shard_key_buyer_id` USING BTREE (`buyer_id`),
    KEY `_gsi_pk_idx_` USING BTREE (`id`)
) ENGINE = InnoDB DEFAULT CHARSET = utf8
PARTITION BY KEY(`buyer_id`)
PARTITIONS 4 |
+-----------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.10 sec)

A tabela de índice contém a chave primária da tabela base, a chave de shard e todas as colunas de cobertura. O atributo AUTO_INCREMENT é removido da coluna de chave primária na tabela de índice, e os índices locais da tabela base também são removidos. Por padrão, um índice globalmente único é criado em todas as chaves de shard da tabela de índice. Esse índice funciona como uma restrição globalmente única da tabela base.

Para limites e precauções sobre o uso de GSIs, consulte Como usar índices secundários globais. Para mais informações sobre SHOW GLOBAL INDEX, consulte SHOW GLOBAL INDEX.

Exemplo: remover um GSI

A remoção de um GSI também remove sua tabela de índice associada.

ALTER TABLE `t_order` DROP INDEX `g_i_seller`;

Renomear um GSI

Por padrão, não é possível renomear índices secundários globais. Para limites e convenções, consulte Como usar índices secundários globais.

Próximos passos