Select into in sql server

In this video we will discuss the power and use of SELECT INTO statement in SQL Server.

We will be using the following 2 tables for the examples.

SQL Script to create Departments and Employees tables

Createtable Departments

(

DepartmentId intprimarykey,

DepartmentName nvarchar(50)

)

Go

Insertinto Departments values (1,'IT')

Insertinto Departments values (2,'HR')

Insertinto Departments values (3,'Payroll')

Go

Createtable Employees

(

Id intprimarykey,

Name nvarchar(100),

Gender nvarchar(10),

Salary int,

DeptId intforeignkeyreferences Departments(DepartmentId)

)

Go

Insertinto Employees values (1,'Mark','Male', 50000, 1)

Insertinto Employees values (2,'Sara','Female', 65000, 2)

Insertinto Employees values (3,'Mike','Male', 48000, 3)

Insertinto Employees values (4,'Pam','Female', 70000, 1)

Insertinto Employees values (5,'John','Male', 55000, 2)

Go

The SELECT INTO statement in SQL Server, selects data from one table and inserts it into a new table.

SELECT INTO statement in SQL Server can do the following1. Copy all rows and columns from an existing table into a new table. This is extremely useful when you want to make a backup copy of the existing table.

SELECT*INTO
EmployeesBackup FROM Employees

2. Copy all rows and columns from an existing table into a new table in an external database.

SELECT*INTO HRDB.dbo.EmployeesBackup FROM Employees

3. Copy only selected columns into a new table

SELECT Id, Name, Gender INTO EmployeesBackup FROM
Employees

4. Copy only selected rows into a new table

SELECT*INTO
EmployeesBackup FROM Employees WHERE DeptId = 1

5. Copy columns from 2 or more table into a new table

SELECT*INTO
EmployeesBackup

FROM Employees

INNERJOIN Departments

ON Employees.DeptId = Departments.DepartmentId

6. Create a new table whose columns and datatypes match with an existing table.

SELECT*INTO
EmployeesBackup FROM Employees WHERE 1 <> 1

7. Copy all rows and columns from an existing table into a new table on a different SQL Server instance. For this, create a linked server and use the 4 part naming convention

SELECT*INTO TargetTable

FROM
[SourceServer].[SourceDB].[dbo].[SourceTable]

Please note : You cannot use SELECT INTO statement to select data into an existing table. For this you will have to use INSERT INTO statement.

Thank you for all your videos, I'm sure everyone makes use of them in his own way, so keep up the great work man :)

I have a question regarding "1 <> 1" to create the table with same schema as the original table: I use "TOP 0" to get the schema of tables (e.g.: "SELECT TOP 0 * FROM MyTable"), and I tried using TOP 0 instead of "WHERE 1 <> 1" and it worked, and so my question is: what is the best way to get the schema to the original table? is it via using "TOP 0" or via using "WHERE 1 <> 1" or something else?