DEV Community

Sardar Mudassar Ali Khan
Sardar Mudassar Ali Khan

Posted on

11

Inserting Data from One Table to Another in SQL using INSERT INTO using SELECT Statement

Sure, if you want to insert data from one table into another in SQL, you can use the INSERT INTO ... SELECT statement. Here's an example:

Let's say you have two tables: table1 and table2, and you want to insert data from table1 into table2.

INSERT INTO table2 (column1, column2, column3)
SELECT column1, column2, column3
FROM table1;
Enter fullscreen mode Exit fullscreen mode

Replace column1, column2, etc., with the actual column names that you want to copy from table1 to table2. The columns you select in the SELECT statement should match the columns you're inserting into in table2.

Keep in mind:

  1. The column names in both tables should correspond in terms of data types and order.
  2. You can add conditions using WHERE in the SELECT statement to filter the data being inserted.

Here's an example with more details:

Let's assume table1 has columns id, name, and age, and you want to insert data into table2 with the same columns:

INSERT INTO table2 (id, name, age)
SELECT id, name, age
FROM table1;
Enter fullscreen mode Exit fullscreen mode

This query will copy all rows from table1 into table2.

Make sure to back up your data before performing such operations, especially when dealing with important databases, to avoid accidental data loss or corruption.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up