The INSERT INTO SELECT statement in SQL allows you to insert data into a table from another table (or the same table). The SELECT query retrieves the data, and the INSERT INTO statement adds it to the target table.
Here’s the basic syntax:
INSERT INTO target_table (column1, column2, column3, ...)
SELECT column1, column2, column3, ...
FROM source_table
WHERE condition;
Explanation:
target_table: The table where the data will be inserted.source_table: The table from which data will be selected.- The
column1, column2, ...should match between thetarget_tableand thesource_tablein both order and type. WHERE conditionis optional. It filters the rows fromsource_tablethat are to be inserted.
Example:
Suppose you have two tables: employees and new_employees. You want to copy employee data from new_employees into the employees table.
INSERT INTO employees (id, first_name, last_name, hire_date)
SELECT id, first_name, last_name, hire_date
FROM new_employees
WHERE hire_date > '2023-01-01';
This will insert all rows from new_employees where the hire_date is after January 1, 2023, into the employees table.
Let me know if you need more examples or further explanation!
No comments:
Post a Comment