SQL

SQL Copy

SQL Copy

This tutorial covers SQL Copy.

Here we explore the concept of copying data from one table to another.

There are two methods of copying data in SQL

This page encompasses:

  • select into
  • insert into select

Here we use two tables. First is the table “student_info” from the previous tutorials, and the second is a table named “grade“, linked to the first table with a foreign key.

idfirstNamelastNameage
1JohnSmith21
2PatrickCasey26
3SamAdams19
4MikeGarciaNULL
5PatrickDumont21
idsubjectNamegradepassedstudentID
1HistoryC11
2PhysicsA12
3HistoryF03
4BiologyA1NULL
5BiologyE15

Select Into

The “select into” clause copies data from an existing table through a query.

The query then inserts the data to a new table. The new table mirrors the column names as well as data types of the original table.

Below is an example.

SELECT * INTO new_table
FROM student_info;

5 rows affected. Now let’s check the new table with the “SELECT * FROM sys.tables;” query. We can also display the result of the new table with the “SELECT * FROM new_table;” statement.

We can also copy only specific columns or records.

For instance.

SELECT firstName, lastName INTO new_copy
FROM student_info
WHERE age BETWEEN 15 AND 25;

3 rows affected.

Insert Into Select

The “insert into select” clause copies data from one table and adds it to another.

Essentially, the query transfers data from an existing table to another existing table. The data types must be identical.

Below is an example

INSERT INTO grade (subjectName)
SELECT firstName FROM student_info;

5 rows affected. We have inserted new data into the “grade” table. So let’s check the outcome.

idsubjectNamegradepassedstudentID
1HistoryC11
2PhysicsA12
3HistoryF03
4BiologyA1NULL
5BiologyE15
6JohnNULLNULLNULL
7PatrickNULLNULLNULL
8SamNULLNULLNULL
9MikeNULLNULLNULL
10PatrickNULLNULLNULL

Previous: SQL Procedure