Posted by Kyle Hankinson October 24, 2024
Cloning a table is useful for backups, testing, and schema experiments. Every database can do it, but what gets copied varies.
CREATE TABLE users_copy AS SELECT * FROM users;
Warning: This copies data and column definitions but NOT indexes, primary keys, auto-increment, or foreign keys.
CREATE TABLE users_copy LIKE users;
LIKE copies the full structure including indexes and auto-increment. To then copy data:
INSERT INTO users_copy SELECT * FROM users;
CREATE TABLE active_users AS
SELECT * FROM users WHERE status = 'active';
CREATE TABLE users_copy AS SELECT * FROM users;
Like MySQL, this does not copy indexes, constraints, or defaults.
CREATE TABLE users_copy (LIKE users INCLUDING ALL);
INCLUDING ALL copies defaults, constraints, indexes, comments, and identity columns. You can be selective:
CREATE TABLE users_copy (LIKE users INCLUDING DEFAULTS INCLUDING CONSTRAINTS);
Then copy data separately:
INSERT INTO users_copy SELECT * FROM users;
SELECT * INTO users_copy FROM users;
SELECT INTO creates the new table automatically. It copies column definitions and data but not indexes, constraints, or triggers.
SELECT * INTO users_copy FROM users WHERE 1 = 0;
The WHERE 1 = 0 ensures no rows are copied.
SELECT id, name, email INTO active_users
FROM users WHERE status = 'active';
-- Structure + Data
CREATE TABLE users_copy AS SELECT * FROM users;
-- Structure Only
CREATE TABLE users_copy AS SELECT * FROM users WHERE 1 = 0;
To get the full DDL including indexes and constraints:
SELECT DBMS_METADATA.GET_DDL('TABLE', 'USERS') FROM DUAL;
Then edit the output to change the table name.
-- Structure + Data
CREATE TABLE users_copy AS SELECT * FROM users;
-- Structure Only
CREATE TABLE users_copy AS SELECT * FROM users WHERE 0;
SQLite's CREATE TABLE AS does not copy primary keys or autoincrement.
| Feature | CREATE AS SELECT | LIKE / Structure Copy |
|---|---|---|
| Column names & types | Yes | Yes |
| Data | Yes | No |
| Primary key | No | Yes (MySQL LIKE, PG INCLUDING ALL) |
| Indexes | No | Yes (MySQL LIKE, PG INCLUDING ALL) |
| Auto-increment | No | Yes (MySQL LIKE, PG INCLUDING ALL) |
| Foreign keys | No | No (must add manually) |
| Triggers | No | No |
| Constraints | No | Yes (PG INCLUDING ALL) |
In SQLPro Studio, you can duplicate a table directly from the sidebar. Right-click a table and select "Duplicate Table" to create a copy with the structure and optionally the data — no SQL required.
About the author — Kyle Hankinson is the founder and sole developer of SQLPro Studio and the Hankinsoft Development suite of database tools. He has been building native macOS and iOS applications since 2010.
Try SQLPro Studio — A powerful database manager for MySQL, PostgreSQL, Microsoft SQL Server, SQLite, Oracle, and Snowflake. Available on macOS, iOS, and Windows.
Download Free Trial View Pricing Compare