Insert Into Sql From Another Table

10 min read

The INSERT INTO ... That's why sELECT statement is a fundamental SQL technique used to copy data from one table and populate another in a single atomic operation. In real terms, this approach eliminates the need for intermediate application-level processing, reducing network latency and simplifying data migration, archiving, or reporting workflows. Whether you are building a data warehouse, creating summary tables for analytics, or simply duplicating a subset of records for testing, mastering this syntax is essential for efficient database management.

Quick note before moving on.

Understanding the Core Syntax

At its heart, the command combines the standard INSERT INTO clause with a SELECT query. The database engine executes the SELECT portion first, materializing a result set, and then streams those rows directly into the target table defined in the INSERT INTO clause Turns out it matters..

The basic structure looks like this:

INSERT INTO target_table (column1, column2, column3, ...)
SELECT column1, column2, column3, ...
FROM source_table
WHERE condition;

Critical Rule: The number of columns listed in the INSERT INTO clause must exactly match the number of columns returned by the SELECT statement. What's more, the data types of corresponding columns must be compatible (e.g., inserting an INT into a VARCHAR column might work via implicit conversion, but inserting a VARCHAR containing letters into an INT column will fail) Worth keeping that in mind..

Implicit vs. Explicit Column Listing

You can omit the column list in the INSERT INTO clause if you are inserting values into every column of the target table in the exact order they were defined during table creation:

-- Risky if table schema changes
INSERT INTO target_table
SELECT * FROM source_table;

Best Practice: Always explicitly list columns. Schema changes (like adding a new column to the middle of the table) will break implicit inserts or, worse, silently insert data into the wrong columns if the order shifts. Explicit listing makes the code self-documenting and resilient to schema evolution That's the part that actually makes a difference. Took long enough..

Handling Data Type Conversions and Transformations

One of the most powerful aspects of INSERT INTO ... SELECT is the ability to transform data on the fly. The SELECT statement is not limited to raw column references; it can contain expressions, functions, CASE statements, and string concatenation And that's really what it comes down to. No workaround needed..

Consider a scenario where you are moving data from a legacy customers_raw table (where names are stored as a single full_name string) into a normalized customers table with separate first_name and last_name columns:

INSERT INTO customers (customer_id, first_name, last_name, email, created_at)
SELECT
    id,
    TRIM(SUBSTRING_INDEX(full_name, ' ', 1)),
    TRIM(SUBSTRING(full_name, LENGTH(SUBSTRING_INDEX(full_name, ' ', 1)) + 2)),
    LOWER(email),
    NOW()
FROM customers_raw
WHERE status = 'active';

Here, string manipulation functions parse the name, LOWER() standardizes the email, and NOW() timestamps the migration. This capability turns a simple copy operation into a lightweight ETL (Extract, Transform, Load) pipeline directly inside the database engine.

Common Use Cases and Patterns

1. Creating Backup or Archive Tables

Before running a risky UPDATE or DELETE on a production table, developers often create a snapshot.

CREATE TABLE orders_archive_2023 AS
SELECT * FROM orders WHERE YEAR(order_date) = 2023;

Note: CREATE TABLE ... AS SELECT (CTAS) creates the table structure automatically. INSERT INTO ... SELECT requires the target table to exist beforehand.

2. Populating Dimension Tables in Data Warehousing

In star schema modeling, you frequently need to load distinct values from a staging table into a dimension table.

INSERT INTO dim_product (product_name, category, brand)
SELECT DISTINCT product_name, category, brand
FROM staging_sales_data
WHERE product_name IS NOT NULL;

The DISTINCT keyword ensures you don't violate a Primary Key or Unique constraint on the dimension table Small thing, real impact. Simple as that..

3. Generating Test Data

Developers often need realistic data volumes for performance testing. You can cross-join a small seed table with a numbers table (or recursive CTE) to generate millions of rows instantly It's one of those things that adds up..

INSERT INTO large_test_table (user_id, event_type, event_time)
SELECT
    u.id,
    e.event_type,
    DATE_ADD('2023-01-01', INTERVAL FLOOR(RAND() * 365) DAY)
FROM users u
CROSS JOIN event_types e
CROSS JOIN (SELECT 1 n UNION ALL SELECT 2 UNION ALL SELECT 3) nums; -- Simple multiplier

Managing Constraints, Keys, and Duplicates

Inserting data into a table with constraints (Primary Keys, Unique Indexes, Foreign Keys, Not Null) introduces failure points. Understanding how your specific RDBMS handles violations is crucial.

The "Duplicate Key" Problem

If the target table has a Primary Key or Unique Index, and the SELECT returns a value that already exists, the statement fails. Different databases offer different solutions:

MySQL / MariaDB: INSERT IGNORE or ON DUPLICATE KEY UPDATE

-- Silently skips rows causing duplicate key errors
INSERT IGNORE INTO target_table (id, data)
SELECT id, data FROM source_table;

-- Updates the existing row instead of failing
INSERT INTO target_table (id, data, last_updated)
SELECT id, data, NOW() FROM source_table
ON DUPLICATE KEY UPDATE data = VALUES(data), last_updated = VALUES(last_updated);

PostgreSQL: ON CONFLICT DO NOTHING / DO UPDATE

INSERT INTO target_table (id, data)
SELECT id, data FROM source_table
ON CONFLICT (id) DO UPDATE SET data = EXCLUDED.data;

SQL Server: MERGE Statement or NOT EXISTS SQL Server does not support ON DUPLICATE KEY syntax directly in INSERT. The standard pattern uses a LEFT JOIN or NOT EXISTS filter in the SELECT clause to prevent attempting the insert in the first place:

INSERT INTO target_table (id, data)
SELECT s.id, s.data
FROM source_table s
LEFT JOIN target_table t ON s.id = t.id
WHERE t.id IS NULL; -- Only insert if ID doesn't exist in target

Identity / Auto-Increment Columns

If the target table has an auto-incrementing Primary Key (Identity in SQL Server, AUTO_INCREMENT in MySQL, SERIAL/IDENTITY in Postgres), you typically exclude that column from the INSERT list. The database generates the value automatically That's the part that actually makes a difference..

-- Correct: Omit 'id' column
INSERT INTO logs (message, severity, created_at)
SELECT message, severity, created_at FROM raw_logs;

If you must preserve specific ID values from the source (e.g., during a migration where foreign keys reference these IDs), you may need to enable explicit identity insertion:

  • SQL Server: SET IDENTITY_INSERT target_table ON;
  • PostgreSQL: Requires setting the sequence value manually after the insert or using OVERRIDING SYSTEM VALUE (Postgres 10+).

Not the most exciting part, but easily the most useful.

Performance Optimization Strategies

Moving millions of rows via INSERT INTO ... SELECT can lock tables, bloat transaction logs, and consume significant I/O. Here are strategies to mitigate impact:

1. Batch Processing (Chunking)

Instead of one massive transaction, loop through the source data in manageable chunks (e.g., 5,000 - 50,000 rows). This keeps transaction logs small, reduces lock escalation, and allows for resume capability if

Chunking the operation is only half the story; the real gain comes from controlling the size of each transaction. A practical approach is to iterate over the source dataset using a key‑based range, for example:

DECLARE @batchSize INT = 10000;
DECLARE @lastId INT = 0;

WHILE 1 = 1
BEGIN
    ;WITH next_set AS (
        SELECT TOP (@batchSize) id, data
        FROM source_table
        WHERE id > @lastId
        ORDER BY id
    )
    INSERT INTO target_table (data)               -- omit identity column
    SELECT data FROM next_set;

    IF @@ROWCOUNT = 0 BREAK;   -- no more rows to process
    SELECT @lastId = MAX(id) FROM next_set;
END

Because each INSERT finishes with an implicit commit (or an explicit COMMIT after the END block), the transaction log never balloons beyond the batch size. If the process is interrupted, the next iteration can resume from the highest id that was successfully loaded Easy to understand, harder to ignore..

Beyond pure chunking, several other tactics can shrink the footprint of a bulk move:

  • Minimize logging – in SQL Server, adding the TABLOCK hint forces a table‑level lock and enables minimal logging when the target is empty or truncated beforehand. In PostgreSQL, setting the target table to UNLOGGED (or using COPY) reduces WAL generation, at the cost of less crash‑recovery safety.

  • Drop or defer constraints – before the bulk load, disable foreign‑key checks, unique indexes, or triggers that would otherwise fire for every row. Re‑create or re‑enable them after the data is in place; this often yields a multiple‑of‑10 speed improvement.

  • Use bulk‑specific utilities – SQL Server’s bcp or BULK INSERT commands stream data directly from a file, bypassing the query optimizer entirely. PostgreSQL’s COPY command works similarly, and MySQL offers LOAD DATA INFILE. These tools write rows in a contiguous fashion and are usually the fastest path when the source is a flat file And that's really what it comes down to..

  • Parallelize when possible – many modern engines allow multiple concurrent INSERT … SELECT statements against distinct partitions or temporary tables. Splitting the source into N slices (e.g., by modulo of a hash column) and running N sessions can saturate I/O subsystems, but be careful not to exceed lock‑contention thresholds Simple, but easy to overlook..

  • **Monitor and tune

Monitor and tune

Even after you’ve applied the techniques described above, it’s essential to keep an eye on the two most common failure modes:

  1. Insufficient rows per batch – If the TOP (@batchSize) clause pulls far fewer than 10 000 rows, the optimizer may still generate intermediate result sets that trigger extra validation steps, inflating commit times even though the log stays small. A quick way to size the batch safely is to run a short “dry‑run” on a copy of the target table and measure how many rows are returned for each iteration; aim for roughly 5–8 % underfill relative to the actual group size.

  2. Lock contention spikes – Parallel sessions (as suggested by splitting the source on a hash column) can saturate the lock manager if too many concurrent read‑modifies conflicts occur. Track the number of rows locked during the load (sys.dm_exec_sessions → wait_event_type) and the average lock wait time. When these numbers climb above ~30 ms per session, consider:

    • Reducing the number of parallel workers.
    • Adding WITH (NOLOCK) only where absolutely necessary—typically never in production.
    • Using SEMAPHORE or ROWVERSIONID clustering keys so that targeted batches release locks faster.

After each major run, capture baseline metrics such as total elapsed time, rows inserted vs. In practice, expected, transaction log size, CPU usage, and memory pressure. Plot them over several weeks; trends often reveal whether the chosen batch size or parallelism level needs adjustment.

Tuning the heavy‑lift commands

Engine Tool Typical flags
SQL Server bcp -c -s file.csv -t -S id,data -r -z -z forces binary format, reduces network chatter
PostgreSQL COPY FROM '/path/to/file' CSV HEADER INTO 'target_table' WITH (FORMAT csv, IF NOT EXISTS ... ) UNLOGGED = true cuts WAL writes
MySQL `LOAD DATA INFILE file.

Every time you switch to these utilities, re‑measure the row‑per‑second and commit latency. Most of the speed gains come from eliminating the overhead of generating parameter lists and building the execution plan; they also typically leave more room for fine‑tuning the surrounding code Easy to understand, harder to ignore..


Putting it all together – a checklist for a successful bulk move

  • Chunk the source into manageable batches (≈5 k–50 k rows).
  • Adjust @lastId logic to guarantee resume capability.
  • Suppress logging: TABLOCK, UNLOGGED, or disable FK checks before insertion.
  • Defer constraints until after the initial load.
  • put to work native bulk loaders (BULK INSERT, COPY, LOAD DATA INFILE).
  • Parallelize wisely: split by hash or range, limit concurrency, and monitor lock waits.
  • Validate integrity post‑load (row counts, checksum, foreign‑key references).
  • Continuous monitoring: set alerts on transaction log growth, CPU spikes, and response‑time degradation.

By combining small, controlled inserts with the right toolset and keeping a close watch on system behavior, you can shift massive data migrations from hours to minutes while preserving safety nets like crash recovery and rollback.


Conclusion

A bulk data transfer benefits enormously from three pillars: chunked processing, minimal logging, and smart bulk utilities. Think about it: chunking keeps each transaction within a safe transaction boundary, preventing lock escalation and allowing resumable runs. Disabling unnecessary constraints and opting for file‑based loaders reduces WAL generation and optimizes I/O throughput. Finally, parallel execution—balanced against lock contention—maximizes the available bandwidth without compromising consistency. Continual measurement of key metrics ensures that the configuration remains optimal as data volumes or hardware characteristics evolve.

delivering reliable, high‑throughput migrations that keep production systems responsive and data integrity intact. When these practices become part of your standard migration playbook, every future move—whether a one‑time lift‑and‑shift or a recurring ETL job—inherits the same predictability and speed, freeing your team to focus on business logic rather than firefighting performance bottlenecks.

New Content

Latest Batch

Others Explored

If You Liked This

Thank you for reading about Insert Into Sql From Another Table. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home