Todos os produtos
Search
Central de documentação

PolarDB:ALTER TABLE (modo DRDS)

Última atualização: Aug 27, 2026

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

Observações de uso

Não é possível usar a instrução ALTER TABLE para modificar uma chave de shard.

Sintaxe

Nota

Para obter a sintaxe detalhada, consulte a instrução ALTER TABLE do MySQL.

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

Example

  • Adicionar uma coluna

    Adicione uma coluna idcard à tabela user_log:

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

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

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

    Renomeie o índice idcard_idx na tabela user_log para idcard_idx_new:

    ALTER TABLE user_log
        RENAME INDEX `idcard_idx` TO `idcard_idx_new`;
  • Remover um índice local

    Remova o índice idcard_idx da tabela user_log:

    ALTER TABLE user_log
        DROP INDEX idcard_idx;
  • Modificar uma coluna

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

    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 mais informações sobre os princípios básicos, consulte Global secondary indexes.

Modificações de colunas

Em tabelas com GSIs, a sintaxe para modificar colunas é idêntica à das tabelas comuns.

Nota

Ao modificar uma tabela que contém um índice secundário global, as alterações em colunas têm restrições adicionais. Para mais informações sobre os limites e convenções dos GSIs, consulte Create and use global secondary indexes.

Modificações de índices

Sintaxe

ALTER TABLE tbl_name
    alter_specification # For GSI-related changes, only one alter_specification is supported.

alter_specification:
  | ADD GLOBAL {INDEX|KEY} index_name # You must 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 # You must 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

global_secondary_index_option:
    [COVERING (col_name,...)] # Covering Index
    drds_partition_options # Must contain only columns specified in index_sharding_col_name.

# Specify the sharding method for the index table.
drds_partition_options:
    DBPARTITION BY db_sharding_algorithm
    [TBPARTITION BY {table_sharding_algorithm} [TBPARTITIONS num]]
db_sharding_algorithm:
    HASH([col_name])
  | {YYYYMM|YYYYWEEK|YYYYDD|YYYYMM_OPT|YYYYWEEK_OPT|YYYYDD_OPT}(col_name)
  | UNI_HASH(col_name)
  | RIGHT_SHIFT(col_name, n)
  | RANGE_HASH(col_name, col_name, n)
table_sharding_algorithm: 
    HASH(col_name) 
  | {MM|DD|WEEK|MMDD|YYYYMM|YYYYWEEK|YYYYDD|YYYYMM_OPT|YYYYWEEK_OPT|YYYYDD_OPT}(col_name)
  | UNI_HASH(col_name)
  | RIGHT_SHIFT(col_name, n)
  | RANGE_HASH(col_name, col_name, n) 

# 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}

A instrução ALTER TABLE ADD GLOBAL INDEX adiciona um GSI a uma tabela existente. Ela estende a sintaxe do MySQL ao introduzir a palavra-chave GLOBAL para indicar que o índice adicionado é um GSI.

A sintaxe ALTER TABLE { DROP | RENAME } INDEX também permite modificar um GSI. Essas operações apresentam limitações específicas. Para mais informações sobre os limites e convenções dos GSIs, consulte Create and use global secondary indexes.

Para descrições detalhadas das cláusulas de definição de GSI, consulte CREATE TABLE (DRDS mode).

Exemplos

  • Criar um índice secundário global

    Este exemplo cria um GSI único 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 dbpartition by hash(`order_id`);
    # Create a global secondary index
    ALTER TABLE t_order ADD UNIQUE GLOBAL INDEX `g_i_buyer` (`buyer_id`) COVERING (`order_snapshot`) dbpartition by hash(`buyer_id`);
    • Tabela base: t_order usa sharding apenas por banco de dados (não por tabela). O método de sharding do banco de dados é hash na coluna order_id.

    • Tabela de índice: g_i_buyer usa sharding apenas por banco de dados (não por tabela). O método de sharding do banco de dados é hash na coluna buyer_id, e a coluna de cobertura é order_snapshot.

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

    Execute SHOW INDEX para visualizar as informações do índice. Os resultados incluem o índice local na chave de shard order_id e o GSI, indexado em buyer_id e contendo várias colunas de cobertura. Neste exemplo, buyer_id é a chave de shard da tabela de índice. As colunas id e order_id são colunas de cobertura padrão (chave primária e chave de shard da tabela base). A coluna order_snapshot é a coluna de cobertura especificada explicitamente.

    Nota

    Para detalhes sobre limites e convenções de GSI, consulte Create and use global secondary indexes. Para detalhes sobre SHOW INDEX, consulte SHOW INDEX.

    show index from t_order;

    Saída retornada:

    +---------+------------+-----------+--------------+----------------+-----------+-------------+----------+--------+------+------------+----------+---------------+
    | TABLE   | NON_UNIQUE | KEY_NAME  | SEQ_IN_INDEX | COLUMN_NAME    | COLLATION | CARDINALITY | SUB_PART | PACKED | NULL | INDEX_TYPE | COMMENT  | INDEX_COMMENT |
    +---------+------------+-----------+--------------+----------------+-----------+-------------+----------+--------+------+------------+----------+---------------+
    | t_order |          0 | PRIMARY   |            1 | id             | A         |           0 |     NULL | NULL   |      | BTREE      |          |               |
    | t_order |          1 | l_i_order |            1 | order_id       | A         |           0 |     NULL | NULL   | YES  | BTREE      |          |               |
    | t_order |          0 | g_i_buyer |            1 | buyer_id       | NULL      |           0 |     NULL | NULL   | YES  | GLOBAL     | INDEX    |               |
    | t_order |          1 | g_i_buyer |            2 | id             | NULL      |           0 |     NULL | NULL   |      | GLOBAL     | COVERING |               |
    | t_order |          1 | g_i_buyer |            3 | order_id       | NULL      |           0 |     NULL | NULL   | YES  | GLOBAL     | COVERING |               |
    | t_order |          1 | g_i_buyer |            4 | order_snapshot | NULL      |           0 |     NULL | NULL   | YES  | GLOBAL     | COVERING |               |
    +---------+------------+-----------+--------------+----------------+-----------+-------------+----------+--------+------+------------+----------+---------------+

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

    show global index from t_order;

    Saída retornada:

    +---------------------+---------+------------+-----------+-------------+------------------------------+------------+------------------+---------------------+--------------------+------------------+---------------------+--------------------+--------+
    | 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 |
    +---------------------+---------+------------+-----------+-------------+------------------------------+------------+------------------+---------------------+--------------------+------------------+---------------------+--------------------+--------+
    | ZZY3_DRDS_LOCAL_APP | t_order | 0          | g_i_buyer | buyer_id    | id, order_id, order_snapshot | NULL       | buyer_id         | HASH                | 4                  |                  | NULL                | NULL               | PUBLIC |
    +---------------------+---------+------------+-----------+-------------+------------------------------+------------+------------------+---------------------+--------------------+------------------+---------------------+--------------------+--------+

    Visualize a estrutura da tabela de índice. Essa tabela inclui 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 locais da tabela base são excluídos. Um índice único é criado por padrão na chave de shard da tabela de índice para impor uma restrição de unicidade global.

    show create table g_i_buyer;

    Saída retornada:

    +-----------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
    | Table     | Create Table                                                                                                                                                                                                                                                                                                                 |
    +-----------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
    | g_i_buyer | CREATE TABLE `g_i_buyer` (`id` bigint(11) NOT NULL, `order_id` varchar(20) DEFAULT NULL, `buyer_id` varchar(20) DEFAULT NULL, `order_snapshot` longtext, PRIMARY KEY (`id`), UNIQUE KEY `auto_shard_key_buyer_id` (`buyer_id`) USING BTREE) ENGINE=InnoDB DEFAULT CHARSET=utf8 dbpartition by hash(`buyer_id`)               |
    +-----------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
  • Remover um índice secundário global

    Remova o GSI chamado g_i_seller. A tabela de índice correspondente também será removida.

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

    Por padrão, a renomeação de um GSI é restrita. Para detalhes sobre limites e convenções de GSI, consulte Create and use global secondary indexes.