Introduction
Copying values from one table to another in SQL is a common task for database administrators, developers, and data analysts. Consider this: whether you need to duplicate a subset of rows, migrate data between schemas, or create a backup snapshot, understanding the various methods available can save time and prevent errors. This article explains how to copy values from one table to another sql, covering the core syntax, different database platforms, and practical tips to ensure data integrity.
Not obvious, but once you see it — you'll see it everywhere.
Understanding the Basics
The Core Concept
At its heart, copying data in SQL involves two operations:
- Reading the source rows from the original table.
- Writing those rows into a target table.
Most modern RDBMS (Relational Database Management Systems) provide a single statement that performs both actions efficiently: INSERT INTO … SELECT. This command lets you select data from one table and insert it directly into another, eliminating the need for intermediate scripts or manual row‑by‑row processing.
Key Terms
- INSERT INTO SELECT – the primary syntax for copying data.
- SELECT – the query that defines which rows and columns are copied.
- Target table – the destination where the values will be stored.
- Source table – the table containing the data to be copied.
Step‑by‑Step Guide
Below is a clear, ordered list of steps you can follow to copy values from one table to another in SQL. The example uses generic table names (source_table and target_table) and columns (col1, col2, …). Adjust the names to match your actual schema.
-
Verify Schema Compatibility
- Ensure the target table exists.
- Confirm that column names, data types, and constraints in the target table match those you intend to copy.
- If the target table does not exist, create it first with the appropriate structure.
-
Decide on the Column List
- Explicit list: Specify the columns you want to copy. This protects you from mismatches if the tables have different column orders.
- Wildcard: Use
*to copy all columns, but only if the tables are identical in structure.
-
Write the INSERT INTO SELECT Statement
INSERT INTO target_table (col1, col2, col3) SELECT col1, col2, col3 FROM source_table WHERE; - The
WHEREclause is optional; omit it to copy the entire table. - You can add additional clauses such as
ORDER BY,GROUP BY, orDISTINCTif needed.
- The
-
Run the Statement
- Execute the query in your SQL client.
- Check the result set for rows affected (most clients return a count).
-
Validate the Data
- Perform a quick count comparison:
SELECT COUNT(*) FROM source_table; SELECT COUNT(*) FROM target_table; - Spot‑check a few rows to ensure values are accurate.
- Perform a quick count comparison:
-
Handle Duplicate Keys (if applicable)
- If the target table has a primary key or unique constraint, the insert may fail for duplicate values.
- Use
INSERT IGNORE(MySQL) orON CONFLICTclause (PostgreSQL) to manage duplicates gracefully.
Example Scenarios
a) Copy All Columns
INSERT INTO employee_backup (emp_id, name, salary, department)
SELECT emp_id, name, salary, department
FROM employee;
b) Copy Specific Columns
INSERT INTO employee_summary (emp_id, name, dept_name)
SELECT emp_id, name, department_name
FROM employee
WHERE salary > 50000;
c) Copy with Transformation
You can also manipulate data while copying, for instance, converting a salary from USD to EUR:
INSERT INTO employee_salary_usd (emp_id, salary_usd)
SELECT emp_id, salary * 0.92 -- 92% conversion rate
FROM employee;
How It Works Under the Hood
Transactional Behavior
Most databases treat the INSERT INTO SELECT operation as a single transaction. Here's the thing — this means either all selected rows are inserted successfully, or none are, ensuring data consistency. Even so, you can wrap the statement in an explicit transaction (BEGIN TRANSACTION … COMMIT) if you need additional control or want to combine it with other statements Most people skip this — try not to. And it works..
Logging and Performance
- Logging: The operation generates log entries for each inserted row. Large copies can fill the transaction log, so consider batching or disabling non‑essential logging during massive imports.
- Performance Tips:
- Disable indexes on the target table before the copy, then rebuild them afterward.
- Use bulk insert options if your RDBMS supports them (e.g.,
INSERT /*+ APPEND */in Oracle). - Run during off‑peak hours to avoid contention with other workloads.
Database‑Specific Variations
While the core syntax is ANSI‑standard, slight differences exist across platforms.
MySQL
- Supports
INSERT INTO … SELECTdirectly. - Use
INSERT IGNOREto skip rows that would cause duplicate‑key errors.
INSERT IGNORE INTO target_table (col1, col2)
SELECT col1, col2 FROM source_table;
PostgreSQL
- Supports
INSERT INTO … SELECT. - Use
ON CONFLICTto handle duplicate keys:
INSERT INTO target_table (col1, col2)
SELECT col1, col2 FROM source_table
ON CONFLICT (col1) DO NOTHING;
SQL Server
INSERT INTO target_table (col1, col2) SELECT col1, col2 FROM source_table;works as expected.- You can add
OUTPUTclause to capture inserted rows for further processing.
Oracle
- Use
INSERT INTO target_table SELECT … FROM source_table;. - For large copies, consider
APPENDhint:
INSERT /*+ APPEND */ INTO target_table (col1, col2)
SELECT col1, col2 FROM source_table;
Common Pitfalls and How to Avoid Them
- Mismatched Data Types – Always verify that the selected columns’ data types are compatible; implicit conversion may lead to truncation or errors.
- Missing Columns – If you omit a column that has a
NOT NULLconstraint in the target table, the insert will fail. Explicitly list columns to avoid this issue. - Auto‑Generated Keys – If the target table has an identity or serial column,
Auto‑Generated Keys
When the destination table contains an identity, serial, or otherwise generated primary key, the normal “copy‑all” behavior will fail because the source rows cannot provide a unique value for that column. Two common remedies are:
- Force the insertion of a placeholder – For most platforms you can simply set the generated column to a constant (e.g.,
0,NULL, or a next‑value based on row count). - Rewrite the statement to ignore the conflict – In PostgreSQL you can combine
ON CONFLICT … DO NOTHINGwith an explicit value; in MySQL useINSERT IGNORE; in SQL ServerMERGEorINSERT … OUTPUToften eliminates the clash by supplying the next sequence value.
-- Example: force a known value for identity columns in Oracle
INSERT /*+ APPEND */ INTO target_table (emp_id, salary_usd,
created_at, updated_at)
SELECT emp_id, salary * 0.92 AS salary_usd,
CURRENT_TIMESTAMP,
CURRENT_TIMESTAMP
FROM source_table;
-- PostgreSQL alternative for a non‑nullable primary key
INSERT INTO target_table (col1, col2, pk_col)
SELECT col1, col2, gen_pk() FROM source_table
ON CONFLICT (pk_col) DO UPDATE SET col1 = EXCLUDED.col1,
col2 = EXCLUDED.col2,
updated_at = CURRENT_TIMESTAMP;
Beyond the Basics – Practical Tips for Large Copies
| Concern | Recommended Action |
|---|---|
| Transaction Log Growth | Enable bulk‑logging only for the session; disable log_bin or autoincrement triggers during heavy imports. Worth adding: |
| Index Disruption | Remove target indexes (DROP INDEX) before the load, then rebuild them afterward – this prevents lock contention and speeds up range scans. |
| Batch Size & Parallelism | Break the source table into chunks of ~10 000 rows (or whatever your RDBMS suggests for optimal parallelism) and run each chunk as its own transaction. This keeps per‑statement CPU and memory footprint low. |