SQL SELECT INTO Statement

SELECT INTO

SQL SELECT INTO statement is used to create a new table from an existing table with all selected rows and columns. Hence, SELECT INTO statement is also used to backup table data in day to day scenario.

Syntax

SELECT * INTO NewTable

FROM ExistingTable

This syntax will copy all records from existing table to new table so if you want to copy specific columns then you can follow below  syntax too.

SELECT column1, column2, …, columnN

INTO NewTable

FROM ExistingTable

WHERE condition(s)

We will see few examples to demonstrate SELECT INTO statement. Let’s query Student table for the same.

StudentTable

We have 15 records in Student table so we will copy all 15 records to new table name tblNewStudents.

SELECT * INTO tblNewStudents
FROM Student

This query created new table tblNewStudents  and copied all records from table Student to table tblNewStudents. We will select new table to check records as follows.

SELECT INTO

We will consider one more example where we will create a new table with specific columns with condition filter.

SELECT RollNumber, FirstName, Country INTO tblPassStudents
FROM Students 
WHERE RollNumber < 1006

In this example, we have selected three columns RollNumber, FirstName and Country from Student table and inserted those columns to new table tblPassStudents where RollNumber is less than 1006. Now we will select tblPasstudents table and verify the records.

INSERT INTO3

As you can see we have six records with three columns in newly created table.

Reference: Manzoor Siddiqui [www.SQLServerLog.com]

CLICK HERE to watch live practical.

You may also like...

Leave a Reply

Your email address will not be published.