π SQL CLONE TABLE β Duplicate Structure or Structure + Data
π§² Introduction β What is SQL CLONE TABLE?
Cloning a table in SQL means creating an exact copy of an existing tableβs structure, optionally including its data. This is useful for backup, testing, staging, and archive purposes.
π― In this guide, you’ll learn:
- How to clone a table structure only
- How to clone structure with data
- Syntax variations across SQL platforms
β 1. Clone Table Structure Only
-- PostgreSQL / SQL Server / SQLite
CREATE TABLE new_table AS
SELECT * FROM old_table WHERE 1=0;
-- MySQL
CREATE TABLE new_table LIKE old_table;
β Creates a new table with the same column definitions but no data.
π 2. Clone Table Structure + Data
CREATE TABLE new_table AS
SELECT * FROM old_table;
β Copies both schema and data, excluding constraints and indexes (platform-dependent).
π₯ 3. Use INSERT INTO for Existing Target
INSERT INTO existing_table
SELECT * FROM old_table;
β Use when the structure already exists, and you want to copy just the data.
β οΈ 4. Does It Copy Indexes, Keys, Triggers?
| Feature | Copied with CREATE TABLE AS | Copied with CREATE TABLE LIKE |
|---|---|---|
| Columns | β | β |
| Data | β (optional) | β |
| Constraints | β | β (MySQL only) |
| Indexes | β | β (MySQL only) |
| Triggers | β | β |
π 5. Clone with Filters (Partial Copy)
CREATE TABLE top_customers AS
SELECT * FROM customers
WHERE total_spent > 1000;
β Create table clone with filtered subset of original data.
π Best Practices
| β Recommended | β Avoid This |
|---|---|
Use LIKE for index+constraint cloning | Assuming CREATE AS copies everything |
| Add indexes manually if required | Overwriting production tables by accident |
Use clear names (_backup, _copy) | Copying system or temporary tables |
π Summary β Recap & Next Steps
Cloning a table is useful for testing, backup, analysis, and archiving. Choose the method based on whether you want to clone structure, data, or both.
π Key Takeaways:
CREATE TABLE ASclones structure + optionally data (no constraints)CREATE TABLE LIKE(MySQL) includes keys and indexes- Use
INSERT INTO SELECTto clone just the data into an existing table
βοΈ Real-World Relevance:
Used in backups, staging environments, data snapshots, A/B tests, and analytics.
β FAQ β SQL CLONE TABLE
β How do I clone just the structure of a table?
β
Use CREATE TABLE new_table AS SELECT * FROM old_table WHERE 1=0;
β Does CREATE TABLE AS copy constraints and indexes?
β No. Only column names and data types.
β Whatβs the difference between CREATE TABLE LIKE and AS SELECT?
β
LIKE copies constraints and indexes (MySQL); AS copies structure and optionally data.
β Can I clone only some rows into a new table?
β
Yes. Use a WHERE clause to filter data when using AS SELECT.
Share Now :
