Todos os produtos
Search
Central de documentação

PolarDB:ALTER TABLE (modo AUTO)

Última atualização: Aug 27, 2026

Use a instrução ALTER TABLE para modificar o schema de uma tabela, por exemplo, para adicionar colunas, criar índices ou alterar definições de colunas. Esta instrução aplica-se apenas a bancos de dados no modo AUTO.

Observações de uso

Se a versão da sua instância for anterior à 5.4.17-16835173, você não poderá usar a instrução ALTER TABLE para modificar uma chave de shard.

Sintaxe

Nota

Para obter a sintaxe detalhada, consulte MySQL ALTER TABLE.

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

Example

  • Adicionar uma coluna

    Adicione uma coluna chamada idcard à tabela user_log:

    ALTER TABLE user_log
        ADD COLUMN idcard varchar(30);
  • Criar um índice

    Crie um índice chamado idcard_idx na coluna idcard da tabela user_log:

    ALTER TABLE user_log
        ADD INDEX idcard_idx (idcard);
  • Remover um índice

    Remova o índice idcard_idx da tabela user_log:

    ALTER TABLE user_log
        DROP INDEX idcard_idx;
  • Renomear um índice

    Renomeie o índice idcard_idx para idcard_idx_new na tabela user_log:

    ALTER TABLE user_log
        RENAME INDEX `idcard_idx` TO `idcard_idx_new`;
  • Modificar uma coluna

    Altere o tamanho da coluna idcard (tipo varchar) de 30 para 40 na tabela user_log:

    ALTER TABLE user_log
        MODIFY COLUMN idcard varchar(40);

Índices secundários globais

O PolarDB-X oferece suporte ao índice secundário global (GSI). Para entender os princípios subjacentes, consulte Global Secondary Indexes.

Alterações em colunas

Em tabelas com GSI, a sintaxe para modificação de colunas é igual à de tabelas comuns.

Nota

Ao modificar uma coluna em uma tabela com GSI, aplicam-se limitações adicionais. Para mais informações sobre as limitações e convenções de GSIs, consulte Create and use global secondary indexes.

Alterações em índices

Sintaxe

ALTER TABLE tbl_name
    alter_specification # Only one alter_specification is supported for changes related to global secondary indexes.

alter_specification:
  | ADD GLOBAL {INDEX|KEY} index_name # You must explicitly specify the index name for a global secondary index.
      [index_type] (index_sharding_col_name,...)
      global_secondary_index_option
      [index_option] ...
  | ADD [CONSTRAINT [symbol]] UNIQUE GLOBAL
      [INDEX|KEY] index_name # You must explicitly specify the index name for a global secondary index.
      [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

# For more information about the syntax specific to global secondary indexes, see the CREATE TABLE documentation.
global_secondary_index_option:
    [COVERING (col_name,...)] # Covering Index
    partition_options # Includes only the columns specified in index_sharding_col_name.

# Specify the sharding 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

# Partition function definitions
partition_func:
    YEAR
  | TO_DAYS
  | TO_SECOND
  | UNIX_TIMESTAMP
  | MONTH

# Partition list definitions
partition_list_spec:
    hash_partition_list
  | range_partition_list
  | list_partition_list

# Column definitions for Hash/Key partitioned tables
hash_partition_list:
    PARTITIONS partition_count

# Column definitions for Range/Range Columns partitioned tables
range_partition_list:
    range_partition [, range_partition ...]

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

# Column definitions for List/List Columns partitioned tables
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' ]

# The following is 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}

As instruções ALTER TABLE ADD GLOBAL INDEX adicionam um GSI a uma tabela existente. Elas usam a palavra-chave GLOBAL, uma extensão da sintaxe padrão do MySQL, para especificar que o índice é um GSI.

Você também pode usar a instrução ALTER TABLE { DROP | RENAME } INDEX para modificar um GSI. Atualmente, existem algumas limitações ao adicionar um GSI a uma tabela existente. Para mais informações sobre as limitações e convenções de GSIs, consulte Create and use global secondary indexes.

Para obter mais informações sobre as cláusulas de definição de GSI, consulte CREATE TABLE (DRDS mode).

Exemplo

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

    Este exemplo cria um índice globalmente único, um tipo de GSI, em uma tabela existente.

    # Create a table.
    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;
    
    # Create a global secondary index.
    ALTER TABLE t_order ADD UNIQUE GLOBAL INDEX `g_i_buyer` (`buyer_id`) COVERING (`order_snapshot`) partition by key(`buyer_id`) partitions 4;
    • Tabela base: A tabela t_order usa particionamento por chave na coluna order_id.

    • Tabela de índice: A tabela de índice g_i_buyer usa particionamento por chave na coluna buyer_id. A coluna order_snapshot é especificada como coluna de cobertura.

    • Cláusula de definição do índice: UNIQUE GLOBAL INDEX .

    Execute SHOW INDEX para visualizar os índices da tabela base. A saída mostra a chave PRIMARY e o índice secundário local l_i_order, mas não o GSI. O GSI é composto pelas seguintes colunas: buyer_id é a chave de shard da tabela de índice; ID (chave primária da tabela base) e order_id (chave de shard da tabela base) são incluídas como colunas de cobertura padrão; e order_snapshot é uma coluna de cobertura especificada explicitamente.

    Nota

    Para mais informações sobre as limitações e convenções de GSIs, consulte Create and use global secondary indexes. Para detalhes sobre SHOW INDEX, consulte SHOW INDEX.

    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)

    Execute SHOW GLOBAL INDEX para visualizar apenas as informações do GSI. Para mais informações, consulte SHOW GLOBAL INDEX.

    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)
                            

    Visualize a estrutura da tabela de índice. Essa tabela contém a chave primária e a chave de shard da tabela base, além das colunas de cobertura padrão e personalizadas. O atributo AUTO_INCREMENT é removido da coluna de chave primária, e os índices secundários locais da tabela base não são replicados na tabela de índice. Por padrão, para impor uma restrição de unicidade global, um índice único é criado automaticamente na chave de shard 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)
  • Remover um índice secundário global

    Ao remover um GSI, como g_i_seller, a tabela de índice correspondente também é removida.

    # Drop the index.
    ALTER TABLE `t_order` DROP INDEX `g_i_seller`;
  • Renomear um índice

    Por padrão, não é possível renomear um GSI. Para mais informações sobre as limitações e convenções de GSIs, consulte Use global secondary indexes.