Adicione, exclua, mescle, renomeie, inspecione e trunque partições em tabelas do MaxCompute.
Visão geral das operações
Operação | Descrição | Função | Plataformas |
Adiciona uma ou mais partições a uma tabela particionada. | Requer permissão Alter. | Os seguintes ambientes suportam estes comandos: | |
Redefine o | |||
Renomeia valores de partição. | |||
Combina várias partições em uma única partição de destino. | |||
Lista todas as partições de uma tabela. | |||
Exibe metadados de uma partição específica. | |||
Remove uma ou mais partições de uma tabela. | |||
Remove dados das partições sem excluí-las. |
Limitações
|
Restrição |
Limite |
|
Tipos de dados compatíveis com colunas de chave de partição |
TINYINT, SMALLINT, INT, BIGINT, CHAR, VARCHAR, STRING |
|
Níveis máximos de partição por tabela |
6 |
|
Máximo de partições por tabela |
60.000 |
|
Máximo de partições consultadas por vez |
10.000 |
|
Mesclagem de partições em tabelas transacionais |
Não compatível |
Adicionar uma partição
Adicione uma ou mais partições a uma tabela particionada existente.
Observações de uso
Em tabelas com partição multinível, especifique valores para todas as colunas de chave de partição ao adicionar uma partição.
Esta operação adiciona apenas valores de partição, não colunas de chave de partição.
Sintaxe
ALTER TABLE <table_name> ADD [IF NOT EXISTS] PARTITION <pt_spec> [PARTITION <pt_spec> PARTITION <pt_spec>...];
Parâmetros
|
Parâmetro |
Obrigatório |
Descrição |
|
table_name |
Sim |
Nome da tabela particionada. |
|
IF NOT EXISTS |
Não |
Suprime o erro caso a partição já exista. |
|
pt_spec |
Sim |
Partição a adicionar, no formato |
Exemplos
Os exemplos a seguir utilizam uma tabela particionada chamada sale_detail. Para criar esta tabela, consulte Criar e excluir tabelas.
CREATE TABLE IF NOT EXISTS sale_detail(
shop_name STRING,
customer_id STRING,
total_price DOUBLE)
PARTITIONED BY (sale_date STRING, region STRING);
-
Adicionar uma única partição
Adicione uma partição para a região de Hangzhou em dezembro de 2025.
ALTER TABLE sale_detail ADD IF NOT EXISTS PARTITION (sale_date='202512', region='hangzhou'); -
Adicionar várias partições simultaneamente
Adicione duas partições para as regiões de Pequim e Xangai em dezembro de 2025.
ALTER TABLE sale_detail ADD IF NOT EXISTS PARTITION (sale_date='202512', region='beijing') PARTITION (sale_date='202512', region='shanghai'); -
Especificação de partição incompleta (erro)
Especificar apenas parte de uma chave de partição multinível retorna um erro. Tanto
sale_datequantoregionsão obrigatórios.ALTER TABLE sale_detail ADD IF NOT EXISTS PARTITION (sale_date='20260111'); -- Error returned: -- FAILED: ODPS-0130071:[1,58] Semantic analysis exception - provided partition spec does not match table partition spec -
Adicionar uma partição a uma Delta Table
-- Create a Delta Table. CREATE TABLE delta_table_test_par ( pk BIGINT NOT NULL PRIMARY KEY, val BIGINT NOT NULL) PARTITIONED BY (dd STRING, hh STRING) TBLPROPERTIES ("transactional"="true"); -- Add a partition. ALTER TABLE delta_table_test_par ADD PARTITION (dd='01', hh='01'); CREATE TABLE delta_table_test_nonpar ( pk BIGINT NOT NULL PRIMARY KEY, val BIGINT NOT NULL) TBLPROPERTIES ("transactional"="true"); -
Modificar propriedades de uma Delta Table com PK
-- Update the number of buckets for a partitioned PK Delta Table. ALTER TABLE delta_table_test_par SET TBLPROPERTIES("write.bucket.num"="64"); -- Update the number of buckets for a non-partitioned PK Delta Table. -- After the update, historical data is redistributed based on the new bucket count. ALTER TABLE delta_table_test_nonpar REWRITE TBLPROPERTIES("write.bucket.num"="128"); -- Update the retain property. This property specifies the number of hours -- for querying historical data states via Time Travel. ALTER TABLE delta_table_test_par SET TBLPROPERTIES("acid.data.retain.hours"="60");
Após adicionar partições, verifique-as com SHOW PARTITIONS. Consulte Listar todas as partições.
Modificar hora de atualização da partição
A operação touch redefine o LastModifiedTime de uma partição para a hora atual e aciona o recálculo do ciclo de vida.
Observações de uso
Para tabelas com partição multinível, especifique valores para todas as colunas de chave de partição.
Sintaxe
ALTER TABLE <table_name> TOUCH PARTITION (<pt_spec>);
Parâmetros
|
Parâmetro |
Obrigatório |
Descrição |
|
table_name |
Sim |
Nome da tabela particionada. Retorna um erro se a tabela não existir. |
|
pt_spec |
Sim |
Partição a atualizar, no formato |
Exemplos
-- Update the LastModifiedTime of a specific partition in the sale_detail table.
ALTER TABLE sale_detail TOUCH PARTITION (sale_date='202512', region='shanghai');
Modificar um valor de partição
O comando RENAME altera os valores de uma partição existente.
Observações de uso
Esta operação altera apenas valores de partição, não renomeia colunas de chave de partição.
Em tabelas com partição multinível, especifique valores para todas as colunas de chave de partição.
Sintaxe
ALTER TABLE <table_name> PARTITION (<pt_spec>) RENAME TO PARTITION (<new_pt_spec>);
Parâmetros
|
Parâmetro |
Obrigatório |
Descrição |
|
table_name |
Sim |
Nome da tabela particionada. |
|
pt_spec |
Sim |
Especificação atual da partição, no formato |
|
new_pt_spec |
Sim |
Nova especificação da partição, no formato |
Exemplos
-- Rename a partition in the sale_detail table.
ALTER TABLE sale_detail PARTITION (sale_date = '201312', region = 'hangzhou') RENAME TO PARTITION (sale_date = '201310', region = 'beijing');
Mesclar partições
O comando MERGE PARTITION combina várias partições em uma única partição de destino. Os dados movem-se para o destino e as partições de origem são excluídas.
Observações de uso
Não há suporte para tabelas externas.
Mesclar partições de uma tabela clusterizada remove o clustering da partição resultante.
Limite máximo de 4.000 partições por mesclagem.
Sintaxe
ALTER TABLE <table_name> MERGE [IF EXISTS] PARTITION (<predicate>) [, PARTITION(<predicate2>) ...] OVERWRITE PARTITION (<fullpartitionSpec>) [PURGE];
Parâmetros
|
Parâmetro |
Obrigatório |
Descrição |
|
table_name |
Sim |
Nome da tabela particionada. |
|
IF EXISTS |
Não |
Suprime o erro se nenhuma partição corresponder à condição. Caso nenhuma partição se qualifique, o sistema não cria nova partição. Operações simultâneas de |
|
predicate |
Sim |
Condição que as partições de origem devem atender. |
|
fullpartitionSpec |
Sim |
Especificação da partição de destino. |
|
PURGE |
Não |
Limpa o diretório de sessão. Por padrão, logs dos últimos três dias são limpos. Para mais informações, consulte Purge. |
Exemplos
Mesclar partições por condição
-- View current partitions.
SHOW PARTITIONS sale_detail;
-- Sample result:
-- sale_date=202512/region=beijing
-- sale_date=202512/region=shanghai
-- sale_date=202602/region=beijing
-- Merge all partitions where sale_date='202512' into a single destination partition.
ALTER TABLE sale_detail MERGE PARTITION(sale_date='202512') OVERWRITE PARTITION(sale_date='202601', region='hangzhou');
-- View partitions after the merge.
SHOW PARTITIONS sale_detail;
-- Sample result:
-- sale_date=202601/region=hangzhou
-- sale_date=202602/region=beijing
Mesclar partições específicas com PURGE
-- Merge two named partitions into a new destination partition.
ALTER TABLE sale_detail MERGE IF EXISTS
PARTITION(sale_date='202601', region='hangzhou'),
PARTITION(sale_date='202602', region='beijing')
OVERWRITE PARTITION(sale_date='202603', region='shanghai') PURGE;
-- View partitions after the merge.
SHOW PARTITIONS sale_detail;
-- Sample result:
-- sale_date=202603/region=shanghai
Listar todas as partições
Liste todas as partições de uma tabela. Retorna um erro se a tabela não existir ou não for particionada.
Sintaxe
SHOW PARTITIONS <table_name>;
Parâmetros
|
Parâmetro |
Obrigatório |
Descrição |
|
table_name |
Sim |
Nome da tabela particionada. |
Exemplos
-- List all partitions in the sale_detail table.
SHOW PARTITIONS sale_detail;
-- Sample result:
-- sale_date=202603/region=shanghai
Visualizar informações da partição
Exiba metadados de uma partição específica, incluindo tamanho, hora de criação e hora da última modificação.
Sintaxe
DESC <table_name> PARTITION (<pt_spec>);
Parâmetros
|
Parâmetro |
Obrigatório |
Descrição |
|
table_name |
Sim |
Nome da tabela particionada. |
|
pt_spec |
Sim |
Partição a inspecionar, no formato |
Exemplos
-- View information for a specific partition.
DESC sale_detail PARTITION (sale_date='202603',region='shanghai');
-- Sample result:
+------------------------------------------------------------------------------------+
| PartitionSize: 0 |
+------------------------------------------------------------------------------------+
| CreateTime: 2026-01-13 11:35:49 |
| LastDDLTime: 2026-01-13 11:35:49 |
| LastModifiedTime: 2026-01-13 11:35:49 |
+------------------------------------------------------------------------------------+
OK
Excluir uma partição
Remova uma ou mais partições de uma tabela. É possível excluir partições específicas por nome ou usar condições de filtro para exclusão em massa.
A exclusão de partições reduz o uso de armazenamento. Para automatizar a remoção de partições antigas, utilize o recurso Ciclo de vida.
Observações de uso
Cada cláusula de filtro de partição pode referenciar apenas uma coluna de chave de partição.
As funções usadas em expressões de filtro devem ser escalares integradas.
Sintaxe
Excluir partições específicas
-- Delete one partition.
ALTER TABLE <table_name> DROP [IF EXISTS] PARTITION <pt_spec>;
-- Delete multiple partitions.
ALTER TABLE <table_name> DROP [IF EXISTS] PARTITION <pt_spec>,PARTITION <pt_spec>[,PARTITION <pt_spec>....];
Excluir partições por condição de filtro
ALTER TABLE <table_name> DROP [IF EXISTS] PARTITION <partition_filtercondition>;
Parâmetros
|
Parâmetro |
Obrigatório |
Descrição |
|
table_name |
Sim |
Nome da tabela particionada. |
|
IF EXISTS |
Não |
Suprime o erro caso a partição não exista. |
|
pt_spec |
Sim |
Partição a excluir, no formato |
|
partition_filtercondition |
Não |
Obrigatório ao usar exclusão baseada em filtro. Consulte Sintaxe de condição de filtro de partição. |
Sintaxe de condição de filtro de partição
As operações de exclusão e truncamento aceitam a mesma sintaxe de filtro de partição:
partition_filtercondition
: PARTITION (<partition_col> <relational_operators> <partition_col_value>)
| PARTITION (scalar(<partition_col>) <relational_operators> <partition_col_value>)
| PARTITION (<partition_filtercondition1> AND|OR <partition_filtercondition2>)
| PARTITION (NOT <partition_filtercondition>)
| PARTITION (<partition_filtercondition1>)[,PARTITION (<partition_filtercondition2>), ...]
|
Elemento |
Descrição |
|
partition_col |
Nome da coluna de chave de partição. |
|
relational_operators |
Operador relacional. Para detalhes, consulte Operadores. |
|
partition_col_value |
Valor ou expressão regular para comparação com o valor da coluna de chave de partição. O tipo de dados deve corresponder ao tipo da coluna de chave de partição. |
|
scalar() |
Função escalar integrada. Processa o valor da coluna de chave de partição antes da comparação. |
|
NOT, AND, OR |
Operadores lógicos aceitos em uma única cláusula de filtro. |
|
Cláusulas separadas por vírgula |
Várias cláusulas de filtro separadas por vírgulas combinam-se com o operador OR. |
Exemplos
Excluir partições específicas
-- Delete one partition.
ALTER TABLE sale_detail DROP IF EXISTS PARTITION(sale_date='202603',region='shanghai');
-- Delete two partitions at once.
ALTER TABLE sale_detail DROP IF EXISTS PARTITION(sale_date='202412',region='hangzhou'),PARTITION(sale_date='202412',region='shanghai');
Excluir partições por condição de filtro (tabela de nível único)
-- Create a single-level partitioned table with sample partitions.
CREATE TABLE IF NOT EXISTS sale_detail_del(
shop_name STRING,
customer_id STRING,
total_price DOUBLE)
PARTITIONED BY (sale_date STRING);
-- Add partitions.
ALTER TABLE sale_detail_del ADD IF NOT EXISTS
PARTITION (sale_date= '201910') PARTITION (sale_date= '201911') PARTITION (sale_date= '201912')
PARTITION (sale_date= '202001') PARTITION (sale_date= '202002') PARTITION (sale_date= '202003')
PARTITION (sale_date= '202004') PARTITION (sale_date= '202005') PARTITION (sale_date= '202006')
PARTITION (sale_date= '202007');
-- Delete by comparison.
ALTER TABLE sale_detail_del DROP IF EXISTS PARTITION(sale_date < '201911');
ALTER TABLE sale_detail_del DROP IF EXISTS PARTITION(sale_date >= '202007');
-- Delete by pattern matching.
ALTER TABLE sale_detail_del DROP IF EXISTS PARTITION(sale_date LIKE '20191%');
-- Delete by value list.
ALTER TABLE sale_detail_del DROP IF EXISTS PARTITION(sale_date IN ('202002','202004','202006'));
-- Delete by range.
ALTER TABLE sale_detail_del DROP IF EXISTS PARTITION(sale_date BETWEEN '202001' AND '202007');
-- Delete using a scalar function.
ALTER TABLE sale_detail_del DROP IF EXISTS PARTITION(substr(sale_date, 1, 4) = '2020');
-- Delete with OR condition.
ALTER TABLE sale_detail_del DROP IF EXISTS PARTITION(sale_date < '201912' OR sale_date >= '202006');
-- Delete with AND condition.
ALTER TABLE sale_detail_del DROP IF EXISTS PARTITION(sale_date > '201912' AND sale_date <= '202004');
-- Delete with NOT condition.
ALTER TABLE sale_detail_del DROP IF EXISTS PARTITION(NOT sale_date > '202004');
-- Multiple filter clauses separated by commas are combined with OR.
ALTER TABLE sale_detail_del DROP IF EXISTS PARTITION(sale_date < '201911'), PARTITION(sale_date >= '202007');
-- Delete by regular expression.
ALTER TABLE sale_detail_del ADD IF NOT EXISTS
PARTITION (sale_date= '2019-10-05')
PARTITION (sale_date= '2019-10-06')
PARTITION (sale_date= '2019-10-07');
ALTER TABLE sale_detail_del DROP IF EXISTS PARTITION(sale_date RLIKE '2019-\\d+-\\d+');
Excluir partições de uma tabela com partição multinível
-- Create a multi-level partitioned table with sample partitions.
CREATE TABLE IF NOT EXISTS region_sale_detail(
shop_name STRING,
customer_id STRING,
total_price DOUBLE)
PARTITIONED BY (sale_date STRING , region STRING );
-- Add partitions.
ALTER TABLE region_sale_detail ADD IF NOT EXISTS
PARTITION (sale_date= '201910',region = 'shanghai') PARTITION (sale_date= '201911',region = 'shanghai')
PARTITION (sale_date= '201912',region = 'shanghai') PARTITION (sale_date= '202001',region = 'shanghai')
PARTITION (sale_date= '202002',region = 'shanghai') PARTITION (sale_date= '201910',region = 'beijing')
PARTITION (sale_date= '201911',region = 'beijing') PARTITION (sale_date= '201912',region = 'beijing')
PARTITION (sale_date= '202001',region = 'beijing') PARTITION (sale_date= '202002',region = 'beijing');
-- Comma-separated filter clauses are combined with OR.
-- This deletes all partitions where sale_date < '201911' OR region = 'beijing'.
ALTER TABLE region_sale_detail DROP IF EXISTS PARTITION(sale_date < '201911'),PARTITION(region = 'beijing');
-- To combine conditions with AND, place both conditions in a single clause.
-- This deletes only partitions where sale_date < '201911' AND region = 'beijing'.
ALTER TABLE region_sale_detail DROP IF EXISTS PARTITION(sale_date < '201911', region = 'beijing');
Cada cláusula de filtro pode referenciar apenas uma coluna de chave de partição. Usar AND para combinar várias colunas de chave de partição em uma única cláusula de filtro retorna um erro.
-- The following statement fails because it references two partition key columns
-- (sale_date and region) with AND in a single filter clause.
ALTER TABLE region_sale_detail DROP IF EXISTS PARTITION(sale_date < '201911' AND region = 'beijing');
-- Error returned:
-- FAILED: ODPS-0130071:[1,82] Semantic analysis exception - invalid column reference region,
-- partition expression must have one and only one column reference
Truncar uma partição
Remova todos os dados das partições especificadas sem excluir as próprias partições.
Trunque pelo nome exato da partição ou por condição de filtro.
Sintaxe
Truncar partições específicas
TRUNCATE TABLE <table_name> PARTITION <pt_spec>[, PARTITION <pt_spec>....];
Truncar partições por condição de filtro
TRUNCATE TABLE <table_name> PARTITION <partition_filtercondition>;
Parâmetros
Parâmetro | Obrigatório | Descrição |
table_name | Sim | Nome da tabela particionada. |
pt_spec | Sim | Partição a truncar, no formato |
partition_filtercondition | Não | Obrigatório ao usar truncamento baseado em filtro. A condição de filtro não diferencia maiúsculas de minúsculas. Sintaxe: Parâmetros:
|
Exemplos
Truncar partições específicas
-- Truncate one partition.
TRUNCATE TABLE sale_detail PARTITION(sale_date='202601',region='hangzhou');
-- Truncate two partitions at once.
TRUNCATE TABLE sale_detail PARTITION(sale_date='202512',region='hangzhou'), PARTITION(sale_date='202512',region='shanghai');
Truncar partições por condição de filtro
-- Truncate all partitions where sale_date starts with '2025' and region is 'hangzhou'.
TRUNCATE TABLE sale_detail PARTITION(sale_date LIKE '2025%' AND region='hangzhou');
Truncar uma Delta Table não particionada
-- For non-partitioned tables only. Using this on a partitioned table returns an error.
TRUNCATE TABLE non_par_table;