Can I insert from another table?

Yes, you can insert records from one table into another table using the INSERT INTO ... SELECT statement in SQL. This allows you to select data from an existing table and insert it into another table.

Here's the general syntax:

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

Example

Suppose you have two tables: employees and archived_employees. You want to insert records from employees into archived_employees where the employee status is 'inactive'.

INSERT INTO archived_employees (id, name, status)
SELECT id, name, status
FROM employees
WHERE status = 'inactive';

In this example, the INSERT INTO ... SELECT statement copies all inactive employees from the employees table into the archived_employees table.

Make sure that the columns you are selecting match the columns in the target table in terms of data type and order.

0 Comments

no data
Be the first to share your comment!