The INSERT INTO SELECT statement in MySQL allows you to insert records into a table by selecting data from another table. This approach eliminates the need to manually specify values and is extremely useful when working with large datasets, backups, historical data storage, and data synchronization between tables.
VALUES keywordWHEREJOIN
// General syntax to insert records from one table into another
INSERT INTO target_table (column1, column2, column3)
SELECT column1, column2, column3
FROM source_table;
// Copy inactive users into an archive table
INSERT INTO users_archive (user_id, name, email)
SELECT id, name, email
FROM users
WHERE status = 'inactive';
// Insert data using JOIN to combine multiple tables
INSERT INTO order_reports (order_id, customer_name, total_amount)
SELECT o.id, c.name, o.total
FROM orders o
JOIN customers c ON o.customer_id = c.id
WHERE o.status = 'completed';
MySQL first executes the SELECT query and retrieves the matching rows. Each returned row is then inserted into the destination table exactly as if it were manually inserted. The original table remains unchanged unless explicitly modified by another query.
If no rows match the WHERE condition, no data is inserted and no error occurs.
SELECT query alone before executing INSERTemployees and employees_backupWHEREJOIN