How to Copies data from one table into another table in SQL ?
There are multiple methods to copy data from one table to another table in SQL. Here are some of the most commonly used methods:
- Using INSERT INTO SELECT statement: The INSERT INTO SELECT statement copies data from one table and inserts it into another table. The syntax for this statement is as follows:
INSERT INTO destination_table (column1, column2, column3, ...)
SELECT column1, column2, column3, ...
FROM source_table;
For example, if we want to copy all the data from a table called "employees" to a new table called "employees_backup", we can use the following SQL statement:
INSERT INTO employees_backup (employee_id, first_name, last_name, email, hire_date, job_id, salary)
SELECT employee_id, first_name, last_name, email, hire_date, job_id, salary
FROM employees;
- Using CREATE TABLE AS SELECT statement: The CREATE TABLE AS SELECT statement creates a new table and copies the data from the source table into the new table. The syntax for this statement is as follows:
CREATE TABLE new_table AS
SELECT column1, column2, column3, ...
FROM source_table;
For example, if we want to create a new table called "employees_backup" and copy all the data from a table called "employees" into it, we can use the following SQL statement:
CREATE TABLE employees_backup AS
SELECT employee_id, first_name, last_name, email, hire_date, job_id, salary
FROM employees;
- Using SELECT INTO statement: The SELECT INTO statement creates a new table and copies the data from the source table into the new table. The syntax for this statement is as follows:
SELECT column1, column2, column3, ...
INTO new_table
FROM source_table;
For example, if we want to create a new table called "employees_backup" and copy all the data from a table called "employees" into it, we can use the following SQL statement:
SELECT employee_id, first_name, last_name, email, hire_date, job_id, salary
INTO employees_backup
FROM employees;
Note: The SELECT INTO statement is not supported in all SQL databases.