Copying a SQL table is one of those everyday database skills that looks trivial until the moment it isn't. Practically speaking, knowing how to copy a SQL table properly — including its data, its structure, its indexes, and its identity settings — saves you from broken migrations, botched experiments on production data, and long nights rebuilding constraints by hand. This guide covers the fastest methods across MySQL, PostgreSQL, SQL Server, and Oracle, plus the traps that catch even experienced developers Turns out it matters..
Not obvious, but once you see it — you'll see it everywhere.
What "Copying a Table" Actually Means
Before writing any SQL, decide what you want to duplicate. There are three distinct outcomes, and each one needs a different command:
- Structure only — an empty table with the same column names and data types. Useful for staging areas and temporary scaffolding.
- Structure plus data — a full, independent clone you can modify without touching the original.
- A complete replica — columns, data, primary keys, foreign keys, indexes, defaults, auto-increment or identity behaviour, and constraints. This is what you need for real migrations or failover testing.
Most frustration comes from asking for option 2 or 3 and silently receiving only part of it. The quick
The quickest way to get a functional duplicate is to let the engine handle both definition and population in a single statement. Each RDBMS offers a “copy‑as‑you‑go” shortcut that avoids the two‑step pattern of “create empty then insert,” but the details differ enough to matter in production.
MySQL
Structure‑only clone
CREATE TABLE new_table LIKE old_table;
The LIKE clause copies column definitions, default values, column comments, and the auto‑increment counter for integer‑based identity columns. Indexes, foreign‑key constraints, and triggers are not duplicated; you must recreate them manually Worth keeping that in mind..
Structure + data
CREATE TABLE new_table AS
SELECT * FROM old_table;
This creates a fresh table with the same column types and populates it with a snapshot of the source data. The auto‑increment counter is reset to 1 unless you explicitly preserve it:
ALTER TABLE new_table AUTO_INCREMENT = (SELECT MAX(id) FROM old_table) + 1;
Pitfalls
- If the source table contains generated columns, you need to re‑issue the
CREATE TABLE … LIKEafter the data copy, becauseAS SELECTstrips them. - Large tables benefit from
CREATE TABLE … ASinside a transaction (MySQL 8.0+ supportsSTART TRANSACTIONwith DDL) to avoid partial copies if the operation is interrupted.
PostgreSQL
Structure‑only with all attributes
CREATE TABLE new_table (LIKE old_table INCLUDING ALL);
INCLUDING ALL copies column definitions, defaults, storage parameters, constraints, indexes, and even the identity (sequence) values. The sequence is initialized to the current max value of the source column, so subsequent inserts continue the proper numbering Surprisingly effective..
Structure + data (fast, but no constraints)
CREATE TABLE new_table AS
TABLESPACE ts_1 -- optional, for large tables
AS SELECT * FROM old_table;
This creates a heap‑only table without any of the original constraints, indexes, or defaults. You must add them afterwards with ALTER TABLE statements or by re‑running the CREATE … LIKE command It's one of those things that adds up..
Pitfalls
- If the source table uses
SERIALorBIGSERIAL, the sequence is copied but not automatically synced to the max value; runSELECT setval('seq_name', (SELECT max(id) FROM new_table));after the copy. - Partitioned tables require copying each partition individually, or using
CREATE TABLE new_table (LIKE old_table INCLUDING ALL) PARTITION OF old_table FOR VALUES FROM (…)in PostgreSQL 15+.
SQL Server
Structure‑only with identity preservation
SELECT TOP 0 *
INTO new_table
FROM old_table;
The SELECT TOP 0 trick creates an empty table that inherits column definitions, data types, and the identity property (if the source uses IDENTITY). To copy data while preserving the identity seed:
SET IDENTITY_INSERT new_table ON;
INSERT INTO new_table (id, col1, col2)
SELECT id, col1, col2 FROM old_table;
SET IDENTITY_INSERT new_table OFF;
Structure + data (single command)
SELECT *
INTO new_table
FROM old_table;
This creates new_table with the same column list and copies all rows. Identity values are reproduced only when the target table’s identity property matches the source; otherwise you must manage the seed manually.
Pitfalls
- If the source table has computed columns or row‑version columns, they are copied but evaluated against the new table’s context, potentially causing mismatches.
- When the source uses temporal tables or change tracking, those
Finishing the thought about temporal and change‑tracking features, those objects are not propagated automatically; you must recreate the temporal tables or enable change‑tracking on the new table manually, otherwise the history and audit capabilities are lost.
Oracle
Oracle does not support a “LIKE” clause, so the typical route to retain the full definition is to copy the data first and then re‑apply the metadata:
CREATE TABLE new_table AS
SELECT * FROM old_table;
After the copy, extract the DDL of the source table with DBMS_METADATA.GET_DDL, strip the SELECT portion, and run the resulting script against the new table. This re‑
Oracle – Re‑creating the full definition
CREATE TABLE new_table AS
SELECT * FROM old_table;
After the bulk load finishes you have two separate artefacts:
- Data – rows appear in
new_table. - Metadata – only the raw select statement remains; column names, data types, constraints, indexes, default values, and even temporal features are stored in Oracle’s internal system catalog (
USER_TAB_COLUMNS,USER_CONS_COLUMNS, etc.).
To make the second artefact usable again inside new_table:
- Run
DBMS_METADATA.GET_DDL('old_table')(orGET_SCHEMAfor partitioned objects). - Strip everything up to the first
FROMclause, leaving just theDATASYSTEM,TABLOCKS,SEQUENCE,DEFAULT, and any ALTER statements. - Paste that cleaned DDL into a temporary script file and execute it against
new_table.
Take this: a cleaned excerpt might look like:
-- stripped DDL
CREATE OR REPLACE TABLE new_table (
id NUMBER(10) GENERATED ALWAYS AS IDENTITY,
colA VARCHAR2(100),
colB DATE DEFAULT SYSDATE
);
ALTER TABLE new_table ADD CONSTRAINT chk_col_b CHECK (colB IS NOT NULL);
Running this script reproduces the exact column definitions, including generated columns, triggers, and any business rules that were part of the original object. When the source contains partitioned tables, repeat the extraction step for each partition range and apply the corresponding DDL individually; otherwise a single CREATE TABLE … PARTITION OF old_table … FOR VALUES … can be followed by the same metadata‑reapplication procedure.
Temporal & Change‑Tracking Objects
If old_table participates in Oracle’s temporal tables (system‑generated audit history) or uses change tracking (trigger‑based versioning), the automatic propagation described above does not happen. The historical rows and current state live under separate schema objects (OLD_TABLE_HISTORY, NEW_TABLE_TRACKER). Consequently:
- You must either re‑enable temporal mode on the new table (
ALTER TABLE new_table ENABLE TEMPORAL ANALYSIS) or manually restore the history records. - Alternatively, create a new change‑tracking entity on the copy and link it to the new table via triggers. Failure to do so means auditing capabilities are lost once the historic data moves to
new_table.
Quick Checklist Before Going Live
Continuing the “Post‑Bulk‑Load → Metadata Recovery” workflow
After you have executed the stripped DDL on new_table, the copy now carries exactly the same structural definition as the original object—columns, types, default values, generated columns, constraints, indexes, partitions and even temporal audit tables. On the flip side, before the live environment goes into production you should still run through the full pre‑deployment checklist to guard against subtle mismatches between the source system and the replica Took long enough..
Quick Checklist – Final Review Steps
| # | Item | Why It Matters | How to Verify |
|---|---|---|---|
| 1 | Row Count Consistency | Ensures every historical record is present; missing rows indicate a mismatch in the SELECT snapshot. Day to day, |
|
| 8 | Index & Statistics Refresh | Stale statistics can degrade query plans on large loads. That said, | |
| 4 | Check Constraints & Triggers | Business rules (e. That's why | Run ALL_TRIGGER_MONITORING / DBA_OBJECT_SCHEMA for each partition and assert that the START_TIME, END_TIME, and PARTITION KEY definitions align with the original design. g. |
| 7 | Change‑Tracking Links | Trigger‑based versioning must point at the new object. | |
| 6 | Temporal & Audit Tables | Historical rows reside under separate schema objects unless enabled. | Execute TRIGGER LINKED TO new_table checks; ensure NEW_IDENTITY matches existing sequence numbers. |
| 5 | Partitioning Integrity | Partition ranges must be correctly mapped; otherwise queries fail or return wrong slices. | Run ANALYZE new_table FOR ALL and verify REINDEX status. |
| 9 | Foreign Key References | Cross‑table relationships depend on exact column names and constraints. Here's the thing — | Insert a test row without specifying the column; verify the value follows the sequence rule. |
| 10 | Performance Baseline | Load size and workload dictate whether the replica will meet SLA thresholds. | |
| 2 | Data Type Alignment | Oracle can silently coerce fields; hidden casts may break downstream logic. , NOT NULL, CHECK) are enforced only when restored. | |
| 3 | Generated Column Logic | Identity columns (IDENTITY, GENERATED ALWAYS AS IDENTITY) drive auto‑increment sequences. |
Query USER_TAB_COLUMNS / OLD_TABLE_HISTORY for presence; if absent, issue ALTER TABLE new_table ENABLE TEMPORAL ANALYSIS. |
Sample Validation Script (Oracle)
-- Automated sanity check after metadata restoration
BEGIN
SET ROLE READONLY;
-- Row count comparison
EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM new_table';
RA
After confirming that the total number of rows matches what you expect from the source snapshot (item 1), the next logical verification is **Data Type Alignment**. In Oracle a restored object may have been casted automatically, so you should spot‑check a random sample of primary‑key columns against their original definitions.
Short version: it depends. Long version — keep reading.
```sql
-- Spot‑check a few PK values
SELECT rowid AS pk, primary_key_col_name,
existing_type, source_type
FROM (
SELECT 12345 AS rn,
NEW_IDENTITY() AS pk,
COLUMN_NAME('PRIMARY KEY')::VARCHAR AS col_name
FROM dual
) t;
Compare existing_type with source_type for each row; any mismatch signals hidden coercion.
With data types verified, move to Generated Column Logic (item 3). Insert a test row without explicitly supplying the auto‑generated column and observe whether the sequence rule (GENERATED ALWAYS AS IDENTITY) produces the expected value Worth knowing..
INSERT INTO my_table (some_field)
VALUES ('test', NULL);
-- Expected: new_id = next value returned by the identity sequence
Next, Check Constraints & Triggers (item 4). Attempt to violate a NOT NULL condition or a CHECK predicate; a silent violation would only surface after the restore completes.
Then address Partitioning Integrity (item 5). For each partition range, query ALL_TRIGGER_MONITORING / DBA_OBJECT_SCHEMA.PARTITION to make sure the START_TIME, `