Select From One Table And Insert Into Another

7 min read

Select from One Table and Insert into Another: A Complete Educational Guide

In this article you will learn how to select from one table and insert into another using standard SQL commands. We will cover the basic syntax, step‑by‑step procedures, common scenarios, performance tips, and troubleshooting advice. By the end of the guide you will be able to move data between tables confidently, whether you are migrating records, archiving old data, or building an ETL pipeline.

Worth pausing on this one.

Introduction

The ability to select from one table and insert into another is a fundamental operation in relational database management systems (RDBMS). It enables you to copy data, transform it, or populate a new table based on the contents of an existing one. Worth adding: this technique is widely used for data migration, archiving, reporting, and building data warehouses. Understanding the underlying concepts and the exact syntax ensures that your operations are safe, efficient, and error‑free.

Prerequisites and Basic Concepts

Before you can select from one table and insert into another, you need to be familiar with a few core ideas:

  • SELECT: Retrieves data from a source table.
  • FROM: Specifies the source table (or tables) for the SELECT statement.
  • INSERT INTO: Adds new rows to a target table.
  • Target Table Structure: The target table must have columns that match the data you intend to insert, either in number, order, or explicit column list.

SQL keywords such as INSERT, SELECT, and INTO are case‑insensitive in most RDBMS, but using consistent capitalization improves readability The details matter here..

Syntax of INSERT INTO … SELECT

The generic syntax for copying data from one table to another looks like this:

INSERT INTO target_table (column1, column2, ...)
SELECT columnA, columnB, ...
FROM source_table
[WHERE condition];

Key points:

  • Column List: You can specify a list of columns for both the target and the source. If omitted, the statement assumes that all columns in the target table are to be filled, and the SELECT must provide the same number of expressions in the same order.
  • WHERE Clause: Optional, but often used to filter rows before insertion.
  • Multiple Tables: You may join several tables in the SELECT part, as long as the resulting columns align with the target definition.

INSERT INTO … SELECT with Specific Columns

If the target table has a different column order or you only need a subset of columns, list them explicitly:

INSERT INTO employees_archive (emp_id, name, salary, hire_date)
SELECT emp_id, name, salary, hire_date
FROM current_employees
WHERE department = 'Sales';

INSERT INTO … SELECT without Column List

When the column order and count are identical, you can omit the column list:

INSERT INTO backup_table
SELECT * FROM original_table;

Be careful: this approach copies all columns, including any computed or nullable fields, which may cause constraint violations.

Step‑by‑Step Guide

Below is a practical workflow to select from one table and insert into another.

  1. Verify Target Table Structure

    • Check column names, data types, and constraints (PRIMARY KEY, NOT NULL, UNIQUE).
    • Use DESCRIBE target_table; or sp_help target_table; depending on your RDBMS.
  2. Write the SELECT Query

    • Draft the SELECT statement that returns the desired rows.
    • Test it alone to ensure it returns the expected data and row count.
  3. Run the SELECT Independently

    • Execute the SELECT query by itself.
    • Verify the result set size, column order, and data integrity.
  4. Insert the Data

    • Combine the SELECT with INSERT INTO.
    • If you are copying the entire table, you may use INSERT INTO target_table SELECT * FROM source_table;.
    • For filtered inserts, add a WHERE clause.
  5. Wrap in a Transaction (Optional but Recommended)

    • Begin a transaction (BEGIN TRANSACTION;), run the INSERT, then either COMMIT; or ROLLBACK; if something goes wrong.
    • This ensures atomicity and prevents half‑finished data moves.
  6. Check the Result

    • Query the target table to confirm the new rows are present.
    • Use SELECT COUNT(*) FROM target_table WHERE <condition>; to verify row counts.

Example Walkthrough

Suppose you have a table sales and you want to archive last year’s data into sales_archive.

-- 1. Verify structure
DESCRIBE sales_archive;

-- 2. Write SELECT
SELECT sale_id, product_id, quantity, sale_date
FROM sales
WHERE sale_date < '2023-01-01';

-- 3. Insert
INSERT INTO sales_archive (sale_id, product_id, quantity, sale_date)
SELECT sale_id, product_id, quantity, sale_date
FROM sales
WHERE sale_date < '2023-01-01';

-- 4. Transaction (optional)
BEGIN TRANSACTION;
INSERT INTO sales_archive (sale_id, product_id, quantity, sale_date)
SELECT sale_id, product_id, quantity, sale_date
FROM sales
WHERE sale_date < '2023-01-01';
COMMIT;

After the transaction, you can safely delete the archived rows from sales if needed.

Common Scenarios

Data Migration

When moving data from an old system to a new one, you often **select from the legacy table

Data Migration

When moving data from an old system to a new one, you often select from the legacy table and insert into the new table. This is a common pattern for gradual migrations, allowing you to keep both systems running until the transition is complete.

Counterintuitive, but true Small thing, real impact..

Example: Migrating user data from users_old to users_new.

-- Ensure the target table structure is compatible
DESCRIBE users_new;

-- Copy active users, mapping old columns to new ones
INSERT INTO users_new (user_id, username, email, created_at)
SELECT 
    old.user_id,
    old.username,
    old.email,
    old.creation_date AS created_at
FROM users_old AS old
WHERE old.status = 'active';

Key Considerations:

  • Column Mapping: The SELECT clause must explicitly map old columns to new ones, especially if names or data types differ.
  • Data Transformation: You can apply functions (e.g., LOWER(), DATE_FORMAT()) during the SELECT to adapt data to the new schema.
  • Incremental Migration: Use a WHERE clause to copy data in batches (e.g., by date range) to avoid locking issues in large tables.

Data Archiving

Archiving involves moving historical data to a separate table to keep the active table lean and performant. This is similar to the sales_archive example but often includes additional steps like partitioning or moving the archive to a different database And that's really what it comes down to..

Example: Archiving orders older than five years.

-- Step 1: Create the archive table (if not exists)
CREATE TABLE orders_archive LIKE orders;

-- Step 2: Insert archived data
INSERT INTO orders_archive
SELECT * FROM orders
WHERE order_date < DATE_SUB(NOW(), INTERVAL 5 YEAR);

-- Step 3: Delete archived rows from the original table
DELETE FROM orders
WHERE order_date < DATE_SUB(NOW(), INTERVAL 5 YEAR);

Best Practices:

  • Transaction: Wrap the INSERT and DELETE in a transaction to ensure consistency.
  • Indexing: Apply appropriate indexes on the archive table to maintain query performance for historical reports.
  • Storage: Consider moving the archive table to a cheaper storage tier if it's rarely accessed.

Data Synchronization

When you need to keep two tables in sync (e.And g. , a production table and a reporting table), you can use INSERT...SELECT to update the target table with changes from the source. This often involves merging inserts, updates, and deletes.

Example: Synchronizing a product catalog.

-- Insert new products that don't exist in the target
INSERT INTO products_reporting (product_id, name, price)
SELECT p.product_id, p.name, p.price
FROM products_source p
WHERE p.product_id NOT IN (SELECT product_id FROM products_reporting);

-- Update existing products (using a temporary table for updates)
-- This is a simplified example; in practice, you might use a MERGE statement or a more complex update strategy.

Note: For full synchronization, you may need to handle updates and deletes separately. Some databases support MERGE (or UPSERT) for this purpose.

Data Cleaning and Transformation

INSERT...SELECT is also useful for cleaning data during a one-time fix or ETL process. You can apply transformations in the SELECT clause to correct or standardize values.

Example: Cleaning customer data.

-- Create a new table with cleaned data
CREATE TABLE customers_cleaned (
    customer_id INT PRIMARY KEY,
    name VARCHAR(100),
    email VARCHAR(100),
    phone VARCHAR(20)
);

-- Insert cleaned data
INSERT INTO customers_cleaned (customer_id, name, email, phone)
SELECT 
    customer_id,
    TRIM(name),  -- Remove extra spaces
    LOWER(email), -- Standardize email to lowercase
    REGEXP_REPLACE(phone, '[^0-9]', '') AS phone -- Keep only digits in phone
FROM customers
WHERE email IS NOT NULL;

Common Transformations:

  • Trim/Replace: TRIM(), REPLACE() for string cleanup.
  • Case Conversion: UPPER(), LOWER() for consistency.
  • Date Formatting: DATE_FORMAT(), STR_TO_DATE() for standardizing dates.
  • Aggregation: Use GROUP BY to aggregate data (e.g., summing sales by region).

Bulk Data Loading

For large datasets, INSERT...SELECT can be more efficient than loading data from an external file, especially when the source is already in the database. It avoids the overhead of parsing and transferring data.

Example: Loading data from a staging table to a production table.

-- Staging table has raw data from an external source
INSERT INTO sales_fact (sale_date, product_id, region_id, amount)
SELECT 
    STR_TO_DATE(stg.sale_date_str, '%Y-%m-%d') AS sale_date,
    stg.product_id,
    r.region_id,
    stg.amount
FROM sales_staging stg
JOIN regions r ON stg.region_name = r.region_name;

Performance Tips:

  • Disable Indexes: Temporarily disable non-unique indexes on the target table during the insert to speed up the operation.
  • Batch Processing: Process data in batches (e.g., 10,000 rows at a time) to avoid long-running transactions and excessive memory usage.
  • **
Just Dropped

Just Published

If You're Into This

You're Not Done Yet

Thank you for reading about Select From One Table And Insert Into Another. 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