The SQL INSERT INTO SELECT statement is used to copy data from one table and insert it into another table. This operation is useful for transferring data between tables, especially when dealing with large datasets.
The basic syntax of the INSERT INTO SELECT statement is as follows:
INSERT INTO target_table (column1, column2, column3, ...)
SELECT column1, column2, column3, ...
FROM source_table
WHERE condition;
Suppose we have two tables: employees and employees_backup. We want to copy all employees who joined after 2020 from the employees table to the employees_backup table.
INSERT INTO employees_backup (id, name, join_date)
SELECT id, name, join_date
FROM employees
WHERE join_date > '2020-01-01';
The INSERT INTO SELECT statement is efficient for bulk data transfer and helps in maintaining data integrity by ensuring that only specific data is transferred based on conditions.
Console Output:
Data successfully copied to employees_backup table.
When using INSERT INTO SELECT, handling NULL values is crucial to ensure data consistency and avoid errors during insertion.
To handle NULL values, you can use the COALESCE function to provide default values for columns that might contain NULLs.
INSERT INTO employees_backup (id, name, join_date)
SELECT id, COALESCE(name, 'Unknown'), join_date
FROM employees
WHERE join_date IS NOT NULL;
Using COALESCE ensures that the target table does not receive NULL values where they are not allowed, thus maintaining data integrity.
Console Output:
Data inserted with default values for NULLs.
Subqueries can be used within the INSERT INTO SELECT statement to dynamically select data based on complex criteria.
Consider inserting data into the employees_backup table from the employees table where the department is determined by a subquery.
INSERT INTO employees_backup (id, name, join_date)
SELECT id, name, join_date
FROM employees
WHERE department_id IN (SELECT id FROM departments WHERE name = 'Sales');
Using subqueries allows for more flexible and dynamic data selection based on related tables and complex conditions.
Console Output:
Data inserted from Sales department.
Conditional insertion allows for selectively inserting data based on specific criteria, ensuring that only relevant data is transferred.
Insert employees into employees_backup if they belong to the 'IT' department and have a salary greater than 50000.
INSERT INTO employees_backup (id, name, join_date)
SELECT id, name, join_date
FROM employees
WHERE department = 'IT' AND salary > 50000;
Conditional insertion ensures that only data meeting specific business rules is transferred, optimizing database operations and storage.
Console Output:
Selected IT department employees with salary > 50000 inserted.
The INSERT IGNORE statement is useful when you want to insert records but ignore any errors that occur due to duplicate keys or constraints.
Insert data into employees_backup, ignoring any duplicates based on the primary key.
INSERT IGNORE INTO employees_backup (id, name, join_date)
SELECT id, name, join_date
FROM employees;
This method prevents the operation from failing due to duplicate entries, ensuring seamless data transfer.
Console Output:
Data inserted, duplicates ignored.
Batch insertions involve inserting multiple records at once, improving performance by reducing the number of database round trips.
Insert multiple employee records from employees to employees_backup in a single transaction.
INSERT INTO employees_backup (id, name, join_date)
SELECT id, name, join_date
FROM employees
WHERE department = 'HR';
Batch insertions enhance performance and reduce transaction overhead, especially beneficial for large-scale data transfers.
Console Output:
Batch insertion completed successfully.
The INSERT ALL statement allows inserting data into multiple tables in a single operation, enhancing efficiency.
Insert data into both employees_backup and audit_log tables from the employees table.
INSERT ALL
INTO employees_backup (id, name, join_date) VALUES (id, name, join_date)
INTO audit_log (employee_id, action) VALUES (id, 'INSERT')
SELECT id, name, join_date
FROM employees;
Using INSERT ALL reduces the need for multiple insert statements, optimizing database operations and resource usage.
Console Output:
Data inserted into multiple tables successfully.
Error handling during INSERT INTO SELECT operations is crucial to ensure data integrity and smooth database operations.
Use TRY...CATCH blocks or equivalent error handling mechanisms in your database system to manage exceptions and roll back transactions if necessary.
BEGIN TRY
INSERT INTO employees_backup (id, name, join_date)
SELECT id, name, join_date
FROM employees;
END TRY
BEGIN CATCH
PRINT 'Error occurred during insertion.';
ROLLBACK;
END CATCH;
Proper error handling ensures that the database remains consistent and any issues are promptly addressed without affecting the overall operation.
Console Output:
Error occurred during insertion.
Newsletter
Subscribe to our newsletter for weekly updates and promotions.
Wiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterCompany
About usCareersPressCompany
About usCareersPressCompany
About usCareersPressLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesCompany
About usCareersPressCompany
About usCareersPressCompany
About usCareersPressLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesAds Policies