Partilhar via


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.

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 ou coluna, 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 de forma preguiçosa 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 tabelas externas, pode-se 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:

  • ALTER COLUMN
  • ADD COLUMN
  • DROP COLUMN
  • SET TBLPROPERTIES
  • UNSET TBLPROPERTIES
  • modificar 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.

  • ADICIONAR COLUMN

    Adiciona uma ou mais colunas à tabela.

  • ALTER COLUMN

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

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

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

  • ADICIONAR PARTITION

    Adiciona uma ou mais partições à tabela.

  • ELIMINAR PARTITION

    Elimina uma ou mais partições da tabela.

  • PARTITION ... SET LOCALIZAÇÃO

    Define o local de uma partição.

  • RENOMEAR PARTITION

    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.

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

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

  • Desativar TBLPROPERTIES

    Remove uma ou mais propriedades definidas pelo usuário.

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

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

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

Exemplos

Para exemplos de adicionar restrições e alterar colunas em Delta Lake, 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;

-- Alter multiple columns in a single statement
-- 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