ALTER TABLE

Aplica-se a:check marked yes Databricks SQL check marked yes Databricks Runtime

Altera o esquema ou as propriedades de uma tabela.

Para alterações de tipo ou renomeação de colunas no Delta Lake, consulte reescrever os dados.

Para alterar o comentário em uma tabela, você também pode usar COMMENT ON.

Para alterar um STREAMING TABLE, use ALTER STREAMING TABLE.

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 preguiçosamente quando a tabela ou os dependentes forem acessados na próxima vez.

Nota

Quando você adiciona uma coluna a uma tabela Delta existente, não é possível definir um DEFAULT valor. Todas as colunas adicionadas às tabelas Delta são tratadas como NULL para linhas existentes. Depois de adicionar uma coluna, você pode, opcionalmente, definir um valor padrão para a coluna, mas isso só é aplicado para novas linhas inseridas na tabela. Utilize a seguinte sintaxe:

ALTER TABLE table_name ALTER COLUMN column_name SET DEFAULT default_expression

Em mesas estrangeiras, você pode executar apenas 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:

  • COLUNA ALTER
  • ADICIONAR COLUNA
  • SOLTAR COLUNA
  • DEFINIR TBLPROPERTIES
  • UNSET TBLPROPERTIES
  • modificar OTIMIZAÇÃO PREDITIVA

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 |
     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. Se a tabela não puder ser encontrada, o Azure Databricks gerará um erro de TABLE_OR_VIEW_NOT_FOUND .

  • RENAME TOto_table_name

    Renomeia a tabela dentro do mesmo esquema.

  • ADICIONAR COLUNA

    Adiciona uma ou mais colunas à tabela.

  • COLUNA ALTER

    Altera uma propriedade ou o local de uma coluna.

  • SOLTAR COLUNA

    Solte uma ou mais colunas ou campos em uma tabela Delta Lake.

  • RENOMEAR COLUNA

    Renomeia uma coluna ou campo em uma tabela Delta Lake.

  • ADICIONAR RESTRIÇÃO

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

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

  • RESTRIÇÃO DE QUEDA

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

  • DROP FEATURE feature_name [ TRUNCATE HISTORY ]

    Aplica-se a:check marked yes Databricks SQL check marked yes Databricks Runtime 14.1 e superior

    Remove um recurso de uma tabela Delta Lake.

    A remoção de recursos que afetam leitores e escritores requer um processo de duas etapas:

    Consulte os recursos da tabela para obter detalhes.

    • feature_name

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

      São apoiados feature_names :

      • «deletionVectors» ou deletionvectors
        • «v2Checkpoint» ou v2checkpoint

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

    • HISTÓRIA TRUNCATE

      Opcionalmente, permite que você inicie a segunda fase de descartar um recurso leitor-mais-gravador após 24 horas, truncando o histórico da tabela para quando o comando de invocação foi executado.

      Truncar o histórico da tabela limita sua capacidade de executar DESCRIBE HISTORY e executar consultas de viagem no tempo.

  • ADICIONAR PARTIÇÃO

    Adiciona uma ou mais partições à tabela.

  • DROP PARTIÇÃO

    Descarta uma ou mais partições da tabela.

  • PARTIÇÃO ... DEFINIR LOCALIZAÇÃO

    Define o local de uma partição.

  • RENOMEAR PARTIÇÃO

    Substitui as chaves de uma partição.

  • 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.

  • SETCLÁUSULA DE FILTRO DE LINHA

    Aplica-se a:check marked yes Databricks SQL check marked yes Databricks Runtime 12.2 e superior check marked yes Unity Catalog

    Importante

    Esta funcionalidade está em Pré-visualização Pública.

    Adiciona uma função de filtro de linha à tabela. Todas as consultas futuras dessa tabela receberão um subconjunto de suas linhas para as quais a função é avaliada como booleana TRUE. Isso pode ser útil para fins de controle de acesso refinado, em que a função pode inspecionar a identidade e/ou associações de grupo do usuário que invoca para decidir se deseja filtrar determinadas linhas.

  • DROP ROW FILTER

    Aplica-se a:check marked yes Unity Catalog

    Importante

    Esta funcionalidade está em Pré-visualização Pública.

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

  • DEFINIR TBLPROPERTIES

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

  • UNSET TBLPROPERTIES

    Remove uma ou mais propriedades definidas pelo usuário.

  • SET LOCATION

    Move o local de uma tabela.

    SET LOCATION path
    
    • LOCATION path

      path deve 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 TOPrincipal

    Transfere a propriedade da tabela para principal.

    Aplica-se a:check marked yes Databricks SQL warehouse versão 2022.35 ou superior Databricks Runtime 11.2 e superior check marked yes

    SET é permitido como palavra-chave opcional.

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

    Aplica-se a:check marked yes Databricks SQL check marked yes Databricks Runtime 13.3 LTS e superior

    Aplique tags à 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.

  • UNSET TAGS ( tag_name [, ...] )

    Aplica-se a:check marked yes Databricks SQL check marked yes Databricks Runtime 13.3 LTS e superior

    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.

  • Cláusula CLUSTER BY

    Aplica-se a:check marked yes Databricks SQL check marked yes Databricks Runtime 13.3 LTS e superior

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

  • { ENABLE | DISABLE | INHERIT } PREDICTIVE OPTIMIZATION

    Aplica-se a:check marked yes Databricks SQL check marked yes Databricks Runtime 12.2 e superior check marked yes Somente Unity Catalog

    Importante

    Esta funcionalidade está em Pré-visualização Pública.

    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 é a INHERIT partir do esquema.

    Quando a otimização preditiva é explicitamente habilitada ou herdada como habilitada, OTIMIZE e VACUUM serão automaticamente invocados na tabela, conforme apropriado pelo Azure Databricks. Para obter mais detalhes, consulte: Otimização preditiva para Delta Lake.

Exemplos

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

-- RENAME table
> DESCRIBE student;
                col_name data_type comment
 ----------------------- --------- -------
                    name    string    NULL
                  rollno       int    NULL
                     age       int    NULL
 # Partition Information
              # col_name data_type comment
                     age       int    NULL

> ALTER TABLE Student RENAME TO StudentInfo;

-- After Renaming the table
> DESCRIBE StudentInfo;
                col_name data_type comment
 ----------------------- --------- -------
                    name    string    NULL
                  rollno       int    NULL
                     age       int    NULL
 # Partition Information
              # col_name data_type comment
                     age       int    NULL

-- RENAME partition
> 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

-- Add new columns to a table
> DESCRIBE StudentInfo;
                col_name data_type comment
 ----------------------- --------- -------
                    name    string    NULL
                  rollno       int    NULL
                     age       int    NULL
 # Partition Information
              # col_name data_type comment
                     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
 # Partition Information
              # col_name data_type comment
                     age       int    NULL

-- Add a new partition to a table
> 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

-- Drop a partition from the table
> 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

-- Adding multiple partitions to the table
> SHOW PARTITIONS StudentInfo;
 partition
 ---------
    age=11
    age=12
    age=15

> ALTER TABLE StudentInfo ADD IF NOT EXISTS PARTITION (age=18) PARTITION (age=20);

-- After adding multiple partitions to the table
> SHOW PARTITIONS StudentInfo;
 partition
 ---------
    age=11
    age=12
    age=15
    age=18
    age=20

-- ALTER or CHANGE COLUMNS
> DESCRIBE StudentInfo;
                col_name data_type comment
+-----------------------+---------+-------
                    name    string    NULL
                  rollno       int    NULL
                LastName    string    NULL
                     DOB timestamp    NULL
                     age       int    NULL
 # Partition Information
              # col_name data_type comment
                     age       int    NULL

ALTER TABLE StudentInfo ALTER COLUMN name COMMENT "new comment";

--After ALTER or CHANGE COLUMNS
> DESCRIBE StudentInfo;
                col_name data_type     comment
 ----------------------- --------- -----------
                    name    string new comment
                  rollno       int        NULL
                LastName    string        NULL
                     DOB timestamp        NULL
                     age       int        NULL
 # Partition Information
              # col_name data_type     comment
                     age       int        NULL

-- RENAME COLUMN
> ALTER TABLE StudentInfo RENAME COLUMN name TO FirstName;

--After RENAME COLUMN
> DESCRIBE StudentInfo;
                col_name data_type     comment
 ----------------------- --------- -----------
               FirstName    string new comment
                  rollno       int        NULL
                LastName    string        NULL
                     DOB timestamp        NULL
                     age       int        NULL
 # Partition Information
              # col_name data_type     comment
                     age       int        NULL

-- Change the file Location
> ALTER TABLE dbx.tab1 PARTITION (a='1', b='2') SET LOCATION '/path/to/part/ways';

-- SET SERDE/ SERDE Properties (DBR only)
> 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 TABLE PROPERTIES
> ALTER TABLE dbx.tab1 SET TBLPROPERTIES ('winner' = 'loser');

-- DROP TABLE PROPERTIES
> ALTER TABLE dbx.tab1 UNSET TBLPROPERTIES ('winner');

-- 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;

-- Applies three tags to the table named `test`.
> ALTER TABLE test SET TAGS ('tag1' = 'val1', 'tag2' = 'val2', 'tag3' = 'val3');

-- Removes three tags from the table named `test`.
> ALTER TABLE test UNSET TAGS ('tag1', 'tag2', 'tag3');

-- 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');

-- Removes three tags from table `main.schema1.test` column `col1`.
> ALTER TABLE main.schema1.test ALTER COLUMN col1 UNSET TAGS ('tag1', 'tag2', 'tag3');
-- Enables predictive optimization for my_table
> ALTER TABLE my_table ENABLE PREDICTIVE OPTIMIZATION;