![]() |
VOOZH | about |
The INSERT INTO SELECT statement is a DML command used to copy data from one table and insert it into another table. It combines the functionality of both INSERT INTO and SELECT statements to transfer data efficiently.
Syntax:
INSERT INTO target_table (column1, column2, ...)
SELECT column1, column2, ...
FROM source_table
WHERE condition;The INSERT INTO SELECT statement works by selecting data from a source table and directly inserting it into a target table in a single operation. First, we create a demo table, on which we will use the INSERT INTO SELECT statement.
Query to Create new_employees Table:
CREATE TABLE new_employees (
employee_id INT PRIMARY KEY,
employee_name VARCHAR(50),
department VARCHAR(50),
salary DECIMAL(10,2)
);Query:
INSERT INTO new_employees (employee_id, employee_name, department, salary)
SELECT employee_id, employee_name, department, salary
FROM employees
WHERE salary > 55000;Output:
Using a SELECT statement instead of the VALUES clause allows inserting multiple rows in a single INSERT INTO statement. In this example, we use the employees table and assign department_id values based on conditions.
Query:
CREATE TABLE employee_department_mapping (
employee_id INT,
department_id INT
);
When inserting multiple columns from a subquery, the SELECT statement is used directly instead of the VALUES clause. In this case, each subquery returns two columns: employee_id and department_id.
Query:
INSERT INTO employee_department_mapping (employee_id, department_id)
SELECT employee_id, department_id
FROM (
SELECT employee_id, 1 AS department_id FROM employees WHERE salary > 55000
UNION ALL
SELECT employee_id, 2 AS department_id FROM employees WHERE salary <= 55000
UNION ALL
SELECT employee_id, 3 AS department_id FROM employees WHERE salary > 60000
) AS subquery;
Output: