COPY table using SELECT INTO command

SQL

Copying tables in SQL involves duplicating the structure and data from one table to another. SELECT INTO statement in SQL allows us to create a new table based on the result of a query. This is particularly useful when we want to duplicate data from an existing table or when we need to create a table with a specific set of columns based on certain criteria.

Basic Syntax

The basic syntax of the SELECT INTO command is as follows:

SELECT column1, column2, ...
INTO newtable [IN externaldb]
FROM oldtable
WHERE condition;
  • SELECT column1, column2, ...: Specify the columns we want to select from the existing table (oldtable).
  • INTO newtable: Indicate the name of the new table we want to create.
  • [IN externaldb]: Optional. If we want to create the new table in an external database, specify it here.
  • FROM oldtable: Specifying the source table from which we are selecting data.
  • WHERE condition: Optional. Add a condition to filter the rows from the source table before inserting them into the new table.

For Example:

Assume we have a table called products with the following structure:

Table: products

product_idproduct_namecategoryprice
1LaptopElectronics1200
2SmartphoneElectronics800
3BookshelfFurniture150

Now, let’s create a new table named products_copy by copying all columns from the products table:

-- Creating a new table 'products_copy' by copying all columns
SELECT *
INTO products_copy
FROM products;

In this example, the SELECT * statement selects all columns from the products table, and the INTO products_copy statement creates a new table named products_copy based on the result of this selection.

To verify the successful creation of the products_copy table, we can query its contents:

-- Viewing the contents of 'products_copy'
SELECT * FROM products_copy;

Output:

product_idproduct_namecategoryprice
1LaptopElectronics1200
2SmartphoneElectronics800
3BookshelfFurniture150

Copying specific columns

Let’s start by creating a simple database for our examples. Assume we have a table called employees:

Table: employees

emp_idemp_nameemp_salary
1John Doe50000
2Jane Doe60000
3Bob Smith75000

Now, Let’s create a new table named high_earners by selecting employees with salaries greater than $60,000

-- Creating a new table 'high_earners'
SELECT emp_id, emp_name, emp_salary
INTO high_earners
FROM employees
WHERE emp_salary > 60000;

Verify the successful creation of the high_earners table:

-- Viewing the contents of 'high_earners'
SELECT * FROM high_earners;

Output:

emp_idemp_nameemp_salary
2Jane Doe60000
3Bob Smith75000

Creating a Table in an External Database

If we want to create the new table in an external database, we can use the following syntax:

SELECT column1, column2, ...
INTO externaldb.dbo.newtable
FROM oldtable
WHERE condition;