Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
The Exchange Partition command will move a partition from a source table to target table and alter each table's metadata.  The Exchange Partition feature is implemented as part of 
Jira
serverASF JIRA
serverId5aa69414-a9e9-3523-82ec-879b028fb15b
keyHIVE-4095
.  
Exchanging multiple partitions is supported in Hive versions 1.2.21.3.02.0.0+ as part of 
Jira
serverASF JIRA
serverId5aa69414-a9e9-3523-82ec-879b028fb15b
keyHIVE-11745
 

See Language Manual DDL for additional information on the Exchange Partition feature.

When the command is executed, the source table's partition folder in HDFS will be renamed to move it to the destination table's partition folder.  The Hive metastore will be updated to change the metadata of the source and destination tables accordingly.

Constraints
  • The destination table cannot contain the partition to be exchanged.
  • The operation fails in the presence of an index. 
  • This command requires both the source and destination table names to have the same table schema.  
    If the schemas are different, the following exception is thrown:
The tables have different schemas. Their partitions cannot be exchanged

 

Syntax
 
Code Block
alter table <tablename> exchange partition (<(partial)?partition spec>) with table <tablename>


Example usage - Basic

Code Block
--Create two tables, one partitioned by ds, one not partitioned
create table T1(a string, b string) partitioned by (ds string);
create table T2(a string, b string);

 
--Exchange partition data from T2 to T1(ds=1)
alter table T1 exchange partition (ds='1') with table T2 

Note that the schema for T2 is being used for the newly created partition T1(ds=1).


Example usage - Rolling Hourly to Daily Partitions

 

Code Block
--Create two tables, one with multiple partitions, one with a single partition.
create table T1(a string, b string) partitioned by (ds string, hr string);
create table T2(a string, b string) partitioned by (hr string);

--Alter the table, moving partition data where ds='1' from table T2 to table T1 (ds=1) 
alter table T1 exchange partition (ds='1') with table T2 

Note that the schema for T2 is being used for the newly created partition T1(ds=1). Either all the partitions of T1 will get created or the whole operation will fail. All partitions of T2 are dropped.


Example Usage - Exchanging Multiple partitions 

Code Block
languagesql
-- Create two tables, both with multiple partitions
CREATE TABLE t3 (a int) PARTITIONED BY (d1 int, d2 int);
CREATE TABLE t4 (a int) PARTITIONED BY (d1 int, d2 int);

-- Alter the table, moving partition data where d1=1, d2=2 from table T4 to table T3
ALTER TABLE t4 EXCHANGE PARTITION (d1 = 1, d2 = 1) WITH TABLE t3;