ALTER TABLE

Aplica-se a:seleção marcada sim Databricks SQL seleção marcada sim Databricks Runtime

Altera o esquema ou as propriedades de uma tabela.

O ALTER TABLE comando não é suportado para tabelas temporárias. Um erro é devolvido se o ALTER TABLE comando for aplicado a uma tabela temporária. Se a tabela estiver armazenada em cache, o comando limpará os dados armazenados em cache da tabela e todos os seus dependentes que se referem a ela. O cache será preenchido de forma preguiçosa quando a tabela ou os dependentes forem acessados na próxima vez.

Em mesas estrangeiras, só pode executar ALTER TABLE SET OWNER e ALTER TABLE RENAME TO.

Permissões obrigatórias

Se você usar o Catálogo Unity, deverá ter MODIFY permissão para:

  • ALTER COLUMN
  • ADD COLUMN
  • DROP COLUMN
  • SET TBLPROPERTIES
  • UNSET TBLPROPERTIES
  • PREDICTIVE OPTIMIZATION

Se utilizares o Catálogo Unity, deves ter permissão MANAGE ou ser proprietário para:

  • SET OWNER TO

Todas as outras operações requerem a propriedade da tabela.

Sintaxe

ALTER TABLE table_name
    { RENAME TO clause |
      ADD COLUMN clause |
      ALTER COLUMN clause |
      DROP COLUMN clause |
      RENAME COLUMN clause |
      DEFAULT COLLATION clause |
      ADD CONSTRAINT clause |
      DROP CONSTRAINT clause |
      DROP FEATURE clause |
      ADD PARTITION clause |
      DROP PARTITION clause |
      PARTITION SET LOCATION clause |
      RENAME PARTITION clause |
      RECOVER PARTITIONS clause |
      SET { ROW FILTER clause } |
      DROP ROW FILTER |
      SET TBLPROPERTIES clause |
      UNSET TBLPROPERTIES clause |
      SET SERDE clause |
      SET LOCATION clause |
      SET OWNER TO clause |
      SET SERDE clause |
      SET TAGS clause |
      UNSET TAGS clause |
      CLUSTER BY clause |
      PREDICTIVE OPTIMIZATION clause}

Parâmetros

  • table_name

    Identifica a tabela que está sendo alterada. O nome não deve incluir uma especificação temporal ou uma especificação de opções. Se a tabela não puder ser encontrada, o Azure Databricks gerará um erro de TABLE_OR_VIEW_NOT_FOUND .

  • RENAME TO to_table_name

    Renomeia a tabela.

    • to_table_name

      Identifica o nome da nova tabela. O nome não deve incluir uma especificação temporal ou uma especificação de opções.

      Para tabelas do Unity Catalog, o to_table_name deve estar dentro do mesmo catálogo que table_name. Para outras tabelas, o to_table_name deve estar dentro do mesmo esquema que table_name.

      Se to_table_name não for qualificado, é implicitamente qualificado com o esquema atual.

    > ALTER TABLE student RENAME TO student_info;
    
  • ADICIONAR COLUMN

    Adiciona uma ou mais colunas à tabela.

    Quando adiciona uma coluna a uma tabela Delta Lake existente, não pode definir um DEFAULT valor. Todas as colunas adicionadas às tabelas Delta Lake são tratadas como NULL as linhas existentes. Depois de adicionar uma coluna, pode, opcionalmente, definir um valor predefinido para novas linhas usando ALTER COLUMN.

    > DESCRIBE StudentInfo;
                    col_name data_type comment
    ----------------------- --------- -------
                        name    string    NULL
                      rollno       int    NULL
                         age       int    NULL
    
    > ALTER TABLE StudentInfo ADD columns (LastName string, DOB timestamp);
    
    -- After adding new columns to the table
    > DESCRIBE StudentInfo;
                    col_name data_type comment
    ----------------------- --------- -------
                        name    string    NULL
                      rollno       int    NULL
                    LastName    string    NULL
                         DOB timestamp    NULL
                         age       int    NULL
    
    -- Optionally set a default value for new rows
    > ALTER TABLE StudentInfo ALTER COLUMN LastName SET DEFAULT 'unknown';
    

  • ALTER COLUMN

    Altera uma propriedade ou a posição de uma coluna.

    > DESCRIBE StudentInfo;
                    col_name data_type comment
    ----------------------- --------- -------
                        name    string    NULL
                      rollno       int    NULL
                    LastName    string    NULL
                         DOB timestamp    NULL
                         age       int    NULL
    
    > ALTER TABLE StudentInfo ALTER COLUMN name COMMENT "new comment";
    
    -- After altering the column
    > DESCRIBE StudentInfo;
                    col_name data_type     comment
    ----------------------- --------- -----------
                        name    string new comment
                      rollno       int        NULL
                    LastName    string        NULL
                         DOB timestamp        NULL
                         age       int        NULL
    

    Alterar várias colunas numa única instrução:

    -- Create a table with 3 columns
    > CREATE TABLE my_table (num INT, str STRING, bool BOOLEAN) TBLPROPERTIES('delta.feature.allowColumnDefaults' = 'supported')
    > DESCRIBE TABLE my_table;
      col_name    data_type     comment
      --------    ---------     -------
           num          int        null
           str       string        null
           bool      boolean       null
    
    -- Update comments on multiple columns
    > ALTER TABLE table ALTER COLUMN
       num COMMENT 'number column',
       str COMMENT 'string column';
    
    > DESCRIBE TABLE my_table;
      col_name    data_type      comment
      --------    ---------   -------------
           num          int   number column
           str       string   string column
          bool      boolean            null
    
    -- Can mix different types of column alter
    > ALTER TABLE table ALTER COLUMN
       bool COMMENT 'boolean column',
       num AFTER bool,
       str AFTER num,
       bool SET DEFAULT true;
    
    > DESCRIBE TABLE my_table;
      col_name    data_type      comment
      --------    ---------   --------------
          bool      boolean   boolean column
           num          int    number column
           str       string    string column
    
  • ELIMINAR COLUMN

    Remova uma ou mais colunas ou campos numa tabela Delta Lake.

  • RENOMEAR COLUMN

    Renomeia uma coluna ou campo em uma tabela Delta Lake.

    > ALTER TABLE StudentInfo RENAME COLUMN name TO FirstName;
    
    -- After renaming the column
    > DESCRIBE StudentInfo;
                    col_name data_type     comment
    ----------------------- --------- -----------
                   FirstName    string new comment
                      rollno       int        NULL
                    LastName    string        NULL
                         DOB timestamp        NULL
                         age       int        NULL
    

  • ADD CONSTRAINT

    Adiciona uma restrição de verificação, restrição de chave estrangeira indicativa ou restrição de chave primária indicativa à tabela.

    Chaves estrangeiras e chaves primárias são suportadas apenas para tabelas no catálogo Unity, não para o catálogo hive_metastore.

  • DEFAULT COLLATION collation_name

    Aplica-se a:marcado como sim Databricks SQL marcado como sim Databricks Runtime 16.3 e superior

    Altera o agrupamento padrão da tabela para novas colunas STRING. As colunas existentes não são afetadas por esta cláusula. Para alterar o agrupamento de uma coluna existente, use ALTER TABLE ... ALTER COLUMN ... COLLATE collation_name.

  • DROP CONSTRAINT

    Elimina uma chave primária, chave estrangeira ou restrição de verificação da tabela.

  • DROP FEATURE feature_name [ TRUNCATE HISTORY ]

    Aplica-se a:marcado com sim Databricks Runtime 14.3 LTS e superior

    O suporte herdado para DROP FEATURE está disponível a partir do Databricks Runtime 14.3 LTS. Para obter a documentação da funcionalidade herdada, consulte Drop Delta table features (legacy).

    Aplica-se a:marcado como sim Databricks SQL marcado como sim Databricks Runtime 16.3 e superior

  • O Azure Databricks recomenda o uso do Databricks Runtime 16.3 e superior para todos os DROP FEATURE comandos, que substitui o comportamento herdado.

    Remove um recurso de uma tabela Delta Lake.

    A remoção de uma funcionalidade pode resultar na adição do recurso de gravador no protocolo de tabela checkpointProtection. Para obter mais informações, consulte Recursos da tabela Drop Delta e Recursos da tabela para compatibilidade de protocolo.

    • feature_name

      O nome de um recurso na forma de um STRING literal ou identificador, que deve ser entendido pelo Azure Databricks e ser suportado pela tabela.

      Se o recurso não estiver presente na tabela, o Azure Databricks gerará DELTA_FEATURE_DROP_FEATURE_NOT_PRESENT.

    • HISTÓRIA TRUNCATE

      Remoção de funcionalidades ao truncar o histórico. Isto requer um processo em duas fases:

A remoção de recursos truncando o histórico requer um processo de duas etapas:

  • A primeira invocação limpa vestígios do recurso e informa sobre o sucesso parcial.

  • Em seguida, aguarde até que o período de retenção termine antes de reexecutar a instrução para concluir a remoção.

    Se você iniciar a segunda invocação muito cedo, o Azure Databricks gerará DELTA_FEATURE_DROP_WAIT_FOR_RETENTION_PERIOD ou DELTA_FEATURE_DROP_HISTORICAL_VERSIONS_EXIST.

    Truncar o histórico da tabela limita a sua capacidade de realizar DESCRIBE HISTORY e de executar consultas de retrospetiva temporal.

    -- Drop the "deletion vectors" from a Delta table
    > ALTER TABLE my_table DROP FEATURE deletionVectors;
    
    -- 24 hours later
    > ALTER TABLE my_table DROP FEATURE deletionVectors TRUNCATE HISTORY;
    
  • ADICIONAR PARTITION

    Adiciona uma ou mais partições à tabela.

    > SHOW PARTITIONS StudentInfo;
    partition
    ---------
        age=11
        age=12
        age=15
    
    > ALTER TABLE StudentInfo ADD IF NOT EXISTS PARTITION (age=18);
    
    -- After adding a new partition to the table
    > SHOW PARTITIONS StudentInfo;
    partition
    ---------
        age=11
        age=12
        age=15
        age=18
    
    -- Adding multiple partitions to the table
    > ALTER TABLE StudentInfo ADD IF NOT EXISTS PARTITION (age=18) PARTITION (age=20);
    
    > SHOW PARTITIONS StudentInfo;
    partition
    ---------
        age=11
        age=12
        age=15
        age=18
        age=20
    
  • ELIMINAR PARTITION

    Elimina uma ou mais partições da tabela.

    > SHOW PARTITIONS StudentInfo;
    partition
    ---------
        age=11
        age=12
        age=15
        age=18
    
    > ALTER TABLE StudentInfo DROP IF EXISTS PARTITION (age=18);
    
    -- After dropping the partition of the table
    > SHOW PARTITIONS StudentInfo;
    partition
    ---------
        age=11
        age=12
        age=15
    
  • PARTITION ... SET LOCALIZAÇÃO

    Define o local de uma partição.

    > ALTER TABLE dbx.tab1 PARTITION (a='1', b='2') SET LOCATION '/path/to/part/ways';
    
  • RENOMEAR PARTITION

    Substitui as chaves de uma partição.

    > SHOW PARTITIONS StudentInfo;
    partition
    ---------
        age=10
        age=11
        age=12
    
    > ALTER TABLE default.StudentInfo PARTITION (age='10') RENAME TO PARTITION (age='15');
    
    -- After renaming Partition
    > SHOW PARTITIONS StudentInfo;
    partition
    ---------
        age=11
        age=12
        age=15
    
  • RECUPERAR PARTIÇÕES

    Instrui o Azure Databricks a verificar o local da tabela e adicionar quaisquer arquivos à tabela que tenham sido adicionados diretamente ao sistema de arquivos.

  • SET ROW FILTER cláusula

    Aplica-se a:assinalado sim Databricks SQL assinalado sim Databricks Runtime 12.2 LTS e superior assinalado sim Unity Catalog somente

    Adiciona uma função de filtro de linha à tabela. Todas as consultas subsequentes à tabela recebem um subconjunto das linhas onde a função é avaliada como booleana TRUE. Isso pode ser útil para fins de controle de acesso refinado, onde a função pode inspecionar a identidade ou as associações de grupo do usuário que invoca para determinar se determinadas linhas devem ser filtradas.

  • DROP ROW FILTER

    Aplica-se a: assinalado como sim apenas ao Unity Catalog

    Descarta o filtro de linha da tabela, se houver. Consultas futuras retornarão todas as linhas da tabela sem qualquer filtragem automática.

  • SET TBLPROPRIEDADES

    Define ou redefine uma ou mais propriedades definidas pelo usuário.

    > ALTER TABLE dbx.tab1 SET TBLPROPERTIES ('winner' = 'loser');
    
  • Desativar TBLPROPERTIES

    Remove uma ou mais propriedades definidas pelo usuário.

    > ALTER TABLE dbx.tab1 UNSET TBLPROPERTIES ('winner');
    
  • SET SERDE

    Aplica-se a: assinalado como sim Databricks Runtime

    Especifica a classe serializer/deserializer (SerDe) usada para ler e escrever dados numa tabela de formato Hive. Também pode configurar propriedades do SerDe com WITH SERDEPROPERTIES.

    > ALTER TABLE test_tab SET SERDE 'org.apache.hadoop.hive.serde2.columnar.LazyBinaryColumnarSerDe';
    
    > ALTER TABLE dbx.tab1 SET SERDE 'org.apache.hadoop' WITH SERDEPROPERTIES ('k' = 'v', 'kay' = 'vee');
    
  • SET LOCATION

    Altera o local de uma tabela.

    SET LOCATION path
    
    • LOCATION path

      path tem de ser um STRING literal. Especifica o novo local para a tabela.

      Os arquivos no local original não serão movidos para o novo local.

  • [ SET ] OWNER TO Principal

    Transfere a propriedade da tabela para principal.

    Aplica-se a:Assinalado como 'sim' Databricks SQL Assinalado como 'sim' Databricks Runtime 11.3 LTS e acima

    SET é permitido como palavra-chave opcional.

  • SET TAGS ( { tag_name = tag_value } [, ...] )

    Aplica-se a:marcado como sim Databricks SQL marcado como sim Databricks Runtime 13.3 LTS e versões superiores

    Aplique etiquetas à tabela. Você precisa ter APPLY TAG permissão para adicionar tags à tabela.

    • tag_name

      Um literal STRING. O tag_name deve ser exclusivo dentro da tabela ou coluna.

    • tag_value

      Um literal STRING.

    -- Applies three tags to the table named `test`.
    > ALTER TABLE test SET TAGS ('tag1' = 'val1', 'tag2' = 'val2', 'tag3' = 'val3');
    
    -- Applies three tags to table `main.schema1.test` column `col1`.
    > ALTER TABLE main.schema1.test ALTER COLUMN col1 SET TAGS ('tag1' = 'val1', 'tag2' = 'val2', 'tag3' = 'val3');
    
  • UNSET TAGS ( tag_name [, ...] )

    Aplica-se a:marcado como sim Databricks SQL marcado como sim Databricks Runtime 13.3 LTS e versões superiores

    Remova as tags da tabela. Você precisa ter APPLY TAG permissão para remover tags da tabela.

    • tag_name

      Um literal STRING. O tag_name deve ser exclusivo dentro da tabela ou coluna.

    -- Removes three tags from the table named `test`.
    > ALTER TABLE test UNSET TAGS ('tag1', 'tag2', 'tag3');
    
    -- Removes three tags from table `main.schema1.test` column `col1`.
    > ALTER TABLE main.schema1.test ALTER COLUMN col1 UNSET TAGS ('tag1', 'tag2', 'tag3');
    
  • CLUSTER BY cláusula

    Aplica-se a:marcado como sim Databricks SQL marcado como sim Databricks Runtime 13.3 LTS e versões superiores

    Adiciona, altera ou descarta a estratégia de clustering para uma tabela Delta Lake.

  • { ENABLE | DISABLE | INHERIT } PREDICTIVE OPTIMIZATION

    Aplica-se a:assinalado sim Databricks SQL assinalado sim Databricks Runtime 12.2 LTS e superior assinalado sim Unity Catalog somente

    Altera a tabela Delta Lake gerenciada para a configuração de otimização preditiva desejada.

    Por padrão, quando as tabelas são criadas, o comportamento é INHERIT a partir do esquema.

    Quando a otimização preditiva é explicitamente ativada ou herdada como ativada, OPTIMIZE e VACUUM serão automaticamente executadas na tabela, conforme apropriado pelo Azure Databricks. Para obter mais detalhes, consulte: Otimização preditiva para tabelas gerenciadas do Unity Catalog.

    -- Enables predictive optimization for my_table
    > ALTER TABLE my_table ENABLE PREDICTIVE OPTIMIZATION;
    

Exemplos adicionais

Para exemplos de adicionar restrições e alterar colunas em Delta Lake, consulte