Explain Codes LogoExplain Codes Logo

How can I create a copy of an Oracle table without copying the data?

sql
table-copy
data-integrity
performance
Anton ShumikhinbyAnton Shumikhin·Aug 12, 2024
TLDR

To create a duplicate structure of an original_table into a new_table without transferring any data, employ CREATE TABLE new_table AS SELECT * FROM original_table WHERE 1=0;. This ensures an exact schema copy.

Understanding the limits

The CREATE TABLE AS SELECT quick-fix has its share of limitations:

  • It fails to clone sequences and triggers, mandating manual recreation post-cloning.
  • Indexes and some constraints aren't carried over, requiring additional steps if they are elemental to your table's operation.
  • While duplicating, materialized view logs don't tag along.
  • It comes up short when it comes to maintaining partitions on partitioned tables.

So, the new table structure looks exactly like the old but doesn't provide all the functional elements.

Advanced steps

Cloning a table requires more than the mere duplication of its structure, devil is in the details. Here are some prominent steps to consider:

Index resurrection

Indexes, being the cornerstones performance, can be resurrected using the CREATE INDEX statement after the creation of the new table structure.

Scripting our way with triggers and sequences

If triggers or sequences were appended to the original table, reapply the same behaviors to the new table by generating the corresponding scripts.

Diving deep into constraints

  • Primary and unique keys: These are cloned during the initial operation; however, reapplying foreign keys and other constraints necessitate manual input.
  • Check constraints: They ensure data integrity and should be scripted from the original table.

Handling partitions like a pro

Managing the partition structure requires complex SQL scripting, often involving manual construction of each partition using a modified CREATE TABLE script.