INSERT INTO SQL Server table with SELECT command


By:
Overview

In some of our earlier examples we used the a SELECT statement to verify the results of the INSERT statements previously issued.  As you know, the INSERT command adds records to a table and the SELECT statement retrieves data from one or more tables.  Did you know that you can use a SELECT statement with an INSERT command to populate a table?  Let's take a look at three examples.

Explanation

In the first example, the INSERT command is used with static values from the SELECT command as shown below:

INSERT INTO [dbo].[Customer]
 ([FirstName]
 ,[LastName]
 ,[PhoneNumber]
 ,[EmailAddress]
 ,[Priority]
 ,[CreateDate])
SELECT 'Karon'
 ,'Sharker'
 ,'333-333-3333'
 ,'[email protected]'
 ,1
 ,'2011-09-15';
GO

In the second example, the INSERT command is used with numerous static values with separate SELECT and UNION commands resulting in three records being inserted as shown below:

INSERT INTO [dbo].[Customer]
 ([FirstName]
 ,[LastName]
 ,[PhoneNumber]
 ,[EmailAddress]
 ,[Priority]
 ,[CreateDate])
SELECT 'Katie', 'QueenCrab', '444-333-3333', '[email protected]', 1,'2011-09-15'
UNION ALL
SELECT 'Jessica', 'TastyTuna', '555-333-3333', '[email protected]', 1,'2011-09-15'
UNION ALL
SELECT 'Sharon', 'WellDoneSteak', '666-333-3333', '[email protected]', 1,'2011-09-15'
GO

In the third example, the INSERT command is used with a SELECT command accessing data from an archive table to populate the dbo.Customer table as shown below:

INSERT INTO [dbo].[Customer]
 ([FirstName]
 ,[LastName]
 ,[PhoneNumber]
 ,[EmailAddress]
 ,[Priority]
 ,[CreateDate])
SELECT [FirstName]
 ,[LastName]
 ,[PhoneNumber]
 ,[EmailAddress]
 ,[Priority]
 ,[CreateDate]
FROM Archive.dbo.Customers_OLD
GO

Last Update: 9/16/2011




Comments For This Article




Friday, December 6, 2019 - 10:43:16 AM - Genti Perja Back To Top (83309)

@ElyasFeyzollahi

Insert into tbl1(col1,col2) -- col3 removed from the list of columns

Select col1,col2 from tbl2


Friday, December 9, 2016 - 2:26:48 AM - ElyasFeyzollahi Back To Top (44928)

Hi how to can i write this code?

Insert into tbl1(col1,col2,col3) 

Select col1,col2 from tbl2 

,'data for col3'

I want insert col3 with out this select and insert manualy

What do i do?















get free sql tips
agree to terms