Observação
O acesso a essa página exige autorização. Você pode tentar entrar ou alterar diretórios.
O acesso a essa página exige autorização. Você pode tentar alterar os diretórios.
Aplica-se a: SQL do Databricks
Databricks Runtime
Altera o esquema ou as propriedades de uma tabela.
Para alterações de tipo ou renomeação de colunas no Delta Lake, confira 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 dependentes que se referem a ela. O cache será preenchido de forma ociosa quando a tabela ou os dependentes forem acessados da próxima vez.
Observação
Quando você adiciona uma coluna a uma tabela Delta existente, não é possível definir um valor DEFAULT
. Todas as colunas adicionadas às tabelas Delta são tratadas como NULL
para linhas existentes. Depois de adicionar uma coluna, opcionalmente você pode definir um valor padrão para a coluna, mas isso só é aplicado para novas linhas inseridas na tabela. Use a seguinte sintaxe:
ALTER TABLE table_name ALTER COLUMN column_name SET DEFAULT default_expression
Em tabelas estrangeiras, você pode executar apenas ALTER TABLE SET OWNER
e ALTER TABLE RENAME TO
.
Permissões necessárias
Se você usar o Catálogo do Unity, deverá ter MODIFY
permissão para:
ALTER COLUMN
ADD COLUMN
DROP COLUMN
SET TBLPROPERTIES
UNSET TBLPROPERTIES
- modificar
PREDICTIVE OPTIMIZATION
Se você usar o Unity Catalog, precisará ter a permissão MANAGE
ou propriedade para:
SET OWNER TO
Todas as outras operações exigem 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
-
Identifica a tabela que está sendo alterada. O nome não deve incluir uma especificação temporal ou especificação de opções. Se a tabela não puder ser encontrada, o Azure Databricks gerará um erro TABLE_OR_VIEW_NOT_FOUND.
RENAME TO
to_table_nameRenomeia a tabela.
-
Identifica o novo nome da tabela. O nome não deve incluir uma especificação temporal ou especificação de opções.
Para tabelas do Catálogo do Unity,
to_table_name
deve estar dentro do mesmo catálogo quetable_name
. Para outras tabelas, oto_table_name
deve estar dentro do mesmo esquema que otable_name
.Se
to_table_name
não for qualificado, ele será automaticamente qualificado com o esquema atual.
-
-
Adiciona uma ou mais colunas à tabela.
-
Altera uma propriedade ou o local de uma coluna.
-
Remover uma ou mais colunas ou campos em uma tabela Delta Lake.
-
Renomeia uma coluna ou campo em uma tabela do Delta Lake.
-
Adiciona uma restrição de verificação, uma restrição de chave estrangeira informativa ou uma restrição de chave primária informativa à tabela.
As chaves estrangeiras e as chaves primárias não têm suporte para tabelas no catálogo
hive_metastore
. DEFAULT COLLATION
collation_nameAplica-se a:
Databricks SQL
Databricks Runtime 16.3 e versões superiores
Altera a ordenação padrão da tabela para novas
STRING
colunas. As colunas existentes não são afetadas por essa cláusula. Para alterar a ordenação de uma coluna existente, useALTER TABLE ... ALTER COLUMN ... COLLATE collation_name
.
-
Remove uma chave primária, uma chave estrangeira ou uma restrição de verificação da tabela.
DROP FEATURE feature_name [ TRUNCATE HISTORY ]
Aplica-se a:
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 a documentação de funcionalidades herdadas, consulte Drop Delta table features (legacy).Aplica-se a:
Databricks SQL
Databricks Runtime 16.3 e versões superiores
O Azure Databricks recomenda o uso do Databricks Runtime 16.3 e superior para todos os
DROP FEATURE
comandos, o que substitui o comportamento herdado.Remove um recurso de uma tabela do Delta Lake.
Remover uma funcionalidade pode resultar na adição da funcionalidade de
checkpointProtection
gravador ao protocolo de tabelas. Para obter mais informações, consulte Os recursos da tabela Drop Delta e os recursos de tabela para compatibilidade de protocolo.feature_name
O nome de um recurso na forma de um literal
STRING
ou identificador, que deve ser compreendido pelo Azure Databricks e ter suporte na tabela.Se o recurso não estiver presente na tabela, o Azure Databricks aciona DELTA_FEATURE_DROP_FEATURE_NOT_PRESENT.
HISTÓRICO DE TRUNCADOS
Remoção de funcionalidades por meio de truncamento do histórico. Isso requer um processo de dois estágios:
A remoção de recursos truncando o histórico requer um processo de duas etapas:
A primeira invocação limpa os rastreamentos do recurso e informa sobre o êxito parcial.
Em seguida, aguarde o término do período de retenção antes de executar novamente 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 sua capacidade de executar DESCRIBE HISTORY e executar consultas de viagem no tempo.
-
Adiciona uma ou mais partições à tabela.
-
Descarta uma ou mais partições da tabela.
-
Define o local de uma partição.
-
Substitui as chaves de uma partição.
-
Instrui o Azure Databricks a verificar o local da tabela e adicionar todos os arquivos à tabela que foram adicionados diretamente ao sistema de arquivos.
Cláusula
SET
ROW FILTERAplica-se a:
SQL do Databricks
Databricks Runtime 12.2 LTS e versões posteriores
Somente Catálogo do Unity
Adiciona uma função de filtro de linha à tabela. Todas as consultas subsequentes à tabela recebem um subconjunto de linhas onde a função avalia como o valor booliano TRUE. Isso pode ser útil para fins de controle de acesso refinado, em que a função pode inspecionar a identidade ou as associações de grupo do usuário que a invocou para determinar se deseja filtrar algumas linhas.
DROP ROW FILTER
Aplica-se a:
Somente Catálogo do Unity
Descarta o filtro de linha da tabela, se houver. Consultas futuras retornarão todas as linhas da tabela sem nenhuma filtragem automática.
-
Configura ou reconfigura uma ou mais propriedades definidas pelo usuário.
-
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 uma literal deSTRING
. Especifica o novo local da tabela.Os arquivos no local original não serão movidos para o novo local.
[ SET ] OWNER TO
principalTransfere a propriedade da tabela para
principal
.Aplica-se a:
SQL do Databricks
Databricks Runtime 11.3 LTS e versões posteriores
SET
é permitido como uma palavra-chave opcional.SET TAGS ( { tag_name = tag_value } [, ...] )
Aplica-se a:
SQL do Databricks
Databricks Runtime 13.3 LTS e versões posteriores
Aplica tags à tabela. Você precisa ter a permissão
APPLY TAG
para adicionar tags à tabela.nome_da_tag
Um literal
STRING
. Otag_name
deve ser exclusivo na tabela ou coluna.tag_value
Um literal
STRING
.
UNSET TAGS ( tag_name [, ...] )
Aplica-se a:
SQL do Databricks
Databricks Runtime 13.3 LTS e versões posteriores
Remove as tags da tabela. Você precisa ter a permissão
APPLY TAG
para remover tags da tabela.nome_da_tag
Um literal
STRING
. Otag_name
deve ser exclusivo na tabela ou coluna.
Cláusula CLUSTER BY
Aplica-se a:
SQL do Databricks
Databricks Runtime 13.3 LTS e versões posteriores
Adiciona, altera ou descarta a estratégia de clustering de uma tabela Delta Lake.
{ ENABLE | DISABLE | INHERIT } PREDICTIVE OPTIMIZATION
Aplica-se a:
SQL do Databricks
Databricks Runtime 12.2 LTS e versões posteriores
Somente Catálogo do Unity
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 é para
INHERIT
do esquema.Quando a otimização preditiva estiver explicitamente habilitada ou herdada como habilitada OPTIMIZE e VACUUM serão automaticamente invocadas na tabela, conforme considerado apropriado pelo Azure Databricks. Para obter mais detalhes, consulte: Otimização preditiva para tabelas gerenciadas do Catálogo do Unity.
Exemplos
Para ver exemplos de adição de restrições e alteração de colunas do Delta Lake, confira
-- 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