Wednesday, December 18, 2024

SQL INSERT INTO SELECT Keyword

 The INSERT INTO SELECT statement in SQL is used to insert data into a table by selecting it from another table. It allows you to copy data from one table to another, possibly with some transformations or conditions.

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 new_employees. You want to copy the data from new_employees into the employees table.

INSERT INTO employees (name, position, salary)
SELECT name, position, salary
FROM new_employees
WHERE salary > 50000;

In this example:

  • Data from new_employees (name, position, and salary) will be inserted into the employees table.
  • The WHERE clause filters the data to only insert records with a salary greater than 50,000.

Notes:

  • The number and order of columns in the INSERT INTO clause must match the number and order of columns in the SELECT statement.
  • The data types of the columns in both the INSERT INTO table and the SELECT result should be compatible.

No comments:

Post a Comment