Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

INSERT INTO SELECT vs VALUES

Tags:

Although there is no reason (apart maybe from aesthetics) to use INSERT INTO SELECT when inserting a single row in a table, is there any difference between using this and INSERT INTO VALUES?

like image 723
User Avatar asked Jul 11 '11 11:07

User


People also ask

What is the difference between insert into and select into?

S.No. INSERT INTO SELECT statement in SQL Server is used to copy data from the source table and insert it into the destination table. The SELECT INTO statement in SQL Server is used to copy data from one (source) table to a new table. INSERT INTO SELECT requires the destination table to be pre-defined.

Which is faster insert into or select into?

INTO' creates the destination table, it exclusively owns that table and is quicker compared to the 'INSERT … SELECT'. Because the 'INSERT … SELECT' inserts data into an existing table, it is slower and requires more resources due to the higher number of logical reads and greater transaction log usage.

What does insert into select statement do?

The INSERT INTO SELECT statement copies data from one table and inserts it into another table. The INSERT INTO SELECT statement requires that the data types in source and target tables match. Note: The existing records in the target table are unaffected.

Can we use insert and select together?

You can use a select-statement within an INSERT statement to insert zero, one, or more rows into a table from the result table of the select-statement. The select-statement embedded in the INSERT statement is no different from the select-statement you use to retrieve data.


1 Answers

Using the INSERT INTO ... SELECT approach allows you to pick your values from another table, based on some criteria.

INSERT INTO dbo.TargetTable(Col1, Col2, ...., ColN)    SELECT Col1, Col2, ..., ColN    FROM dbo.SourceTable    WHERE (some condition) 

That might be a bit easier and more readable to write, rather than having to retrieve 20 values from your source table, stash them into temporary variables, just so you can then call your INSERT INTO dbo.Destination(....) VALUES(......) statement...

DECLARE @Value1 INT DECLARE @Value2 DATETIME .... DECLARE @ValueN INT  SELECT        @Value1 = Col1,       @Value2 = Col2,       ....       @ValueN = ColN FROM      dbo.SourceTable WHERE      (some condition)   INSERT INTO dbo.TargetTable(Col1, Col2, ...., ColN) VALUES(@Value1, @Value2, ....., @ValueN) 

But in the end - it's just an INSERT statement that inserts data - it's really just a matter of personal preference and which approach is easier / more convenient to use....

like image 165
marc_s Avatar answered Sep 29 '22 09:09

marc_s