ALTER TABLE

Sintaxe:

ALTER [ONLINE] [IGNORE] TABLE tbl_name
    alter_specification [, alter_specification] ...

alter_specification:
    table_option ...
  | ADD [COLUMN] col_name column_definition
        [FIRST | AFTER col_name ]
  | ADD [COLUMN] (col_name column_definition,...)
  | ADD {INDEX|KEY} [index_name]
        [index_type] (index_col_name,...) [index_option] ...
  | ADD [CONSTRAINT [symbol]] PRIMARY KEY
        [index_type] (index_col_name,...) [index_option] ...
  | ADD [CONSTRAINT [symbol]]
        UNIQUE [INDEX|KEY] [index_name]
        [index_type] (index_col_name,...) [index_option] ...
  | ADD FULLTEXT [INDEX|KEY] [index_name]
        (index_col_name,...) [index_option] ...
  | ADD SPATIAL [INDEX|KEY] [index_name]
        (index_col_name,...) [index_option] ...
  | ADD [CONSTRAINT [symbol]]
        FOREIGN KEY [index_name] (index_col_name,...)
        reference_definition
  | ALTER [COLUMN] col_name {SET DEFAULT literal | DROP DEFAULT}
  | CHANGE [COLUMN] old_col_name new_col_name column_definition
        [FIRST|AFTER col_name]
  | MODIFY [COLUMN] col_name column_definition
        [FIRST | AFTER col_name]
  | DROP [COLUMN] col_name
  | DROP PRIMARY KEY
  | DROP {INDEX|KEY} index_name
  | DROP FOREIGN KEY fk_symbol
  | DISABLE KEYS
  | ENABLE KEYS
  | RENAME [TO] new_tbl_name
  | ORDER BY col_name [, col_name] ...
  | CONVERT TO CHARACTER SET charset_name [COLLATE collation_name]
  | [DEFAULT] CHARACTER SET [=] charset_name [COLLATE [=] collation_name]
  | DISCARD TABLESPACE
  | IMPORT TABLESPACE
  | partition_options
  | ADD PARTITION (partition_definition)
  | DROP PARTITION partition_names
  | COALESCE PARTITION number
  | REORGANIZE PARTITION [partition_names INTO (partition_definitions)]
  | ANALYZE PARTITION partition_names
  | CHECK PARTITION partition_names
  | OPTIMIZE PARTITION partition_names
  | REBUILD PARTITION partition_names
  | REPAIR PARTITION partition_names
  | REMOVE PARTITIONING

column_definition:
    data_type [NOT NULL | NULL] [DEFAULT default_value]
      [AUTO_INCREMENT] [UNIQUE [KEY] | [PRIMARY] KEY]
      [COMMENT 'string']
      [COLUMN_FORMAT {FIXED|DYNAMIC|DEFAULT}]
      [STORAGE {DISK|MEMORY|DEFAULT}]
  | data_type [GENERATED ALWAYS]  AS   ( <expression> )  {VIRTUAL | PERSISTENT}
      [UNIQUE] [UNIQUE KEY] [COMMENT 'string']

index_col_name:
    col_name [(length)] [ASC | DESC]

index_type:
    USING {BTREE | HASH | RTREE}

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

Descrição:

ALTER TABLE lhe permite alterar a estrutura de uma tabela existente. Por exemplo, você pode adicionar ou excluir colunas, criar ou destruir índices, alterar o tipo de colunas existentes, ou renomear colunas ou a mesma tabela. Você também pode alterar o comentario para a tabela e o tipo de tabela.

Quando é que o ALTER TABLE copia todos os dados?

MySQL/MariaDB têm sempre tido um ALTER TABLE muito rico; você pode fazer todas as mudanças que você precisar com um só comando. Uma desvantagem com isto, tem sido que para a maioria dos casos ALTER TABLE faz uma copia completa da tabela, o que pode demorar muito tempo se a tabela for grande.

Com o passar do tempo mais e mais operações irão ser feitas online (feitas de uma vez ou pelo menos muito rápido). Aqui tem uma lista das coisas que podem ser feitas 'de uma vez' sem ter que copiar a tabela:

  • Mudar o nome de uma coluna
  • Mudar o tamanho de exibição de um inteiro como em INT(2) -> INT(3)
  • Mudar o comentario de uma tabela
  • Adicionar uma nova opção enum no final de uma lista
  • Renomear uma tabela

No MariaDB 5.3, você pode usar ALTER ONLINE TABLE para garantir que seu ALTER TABLE seja imediato; Se não pode ser feito imediatamente você receberá um sinal de erro:

create table t1 (a int, e enum ('red','green'));
alter online table t1 modify e enum('red','green','blue');
-> Query OK, 0 rows affected (0.11 sec)
-> Records: 0  Duplicates: 0  Warnings: 0

alter online table t1 add c int;
-> ERROR 1656 (HY000): Can't execute the given 'ALTER' command as online

Relatórios de Progresso

No MariaDB 5.3 você pode obter relatórios de progresso para ALTER TABLE em clientes que suportem o novo protocolo de relatórios de progresso. Desde o cliente mysql:

MariaDB> alter table test engine=Aria;
Stage: 1 of 2 'copy to tmp table'    46% of stage

O relatório de progresso é também mostrado em SHOW PROCESSLIST e information_schema.processlist.

Veja também:

Comments

Comments loading...
Content reproduced on this site is the property of its respective owners, and this content is not reviewed in advance by MariaDB. The views, information and opinions expressed by this content do not necessarily represent those of MariaDB or any other party.