Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server 'select * into' versus 'insert into ..select *

Say table1 and table2 already exist, is there any difference between these queries

query1 :-

select * into table1 from table2 where 1=1 

query2: -

insert into table1 select * from table2 
like image 772
Sujit Prabhakaran Avatar asked Dec 19 '11 11:12

Sujit Prabhakaran


People also ask

What is the difference between SELECT into and insert into SELECT?

INSERT INTO SELECT vs SELECT INTO: Both the statements could be used to copy data from one table to another. But INSERT INTO SELECT could be used only if the target table exists whereas SELECT INTO statement could be used even if the target table doesn't exist as it creates the target table if it doesn't exist.

Is SELECT into faster than insert 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.

Why SELECT * is not recommended?

When you use select * you're make it impossible to profile, therefore you're not writing clear & straightforward code and you are going against the spirit of the quote. select * is an anti-pattern. So selecting columns is not a premature optimization.

What is insert into SELECT in SQL?

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.


2 Answers

The select * into table1 from table2 where 1=1 creates table1 and inserts the values of table2 in them. So, if the table is already created that statement would give an error.

The insert into table1 select * from table2 only inserts the values of table2 in table1.

like image 112
aF. Avatar answered Sep 20 '22 13:09

aF.


The first one (SELECT INTO) will create and populate a new table the second (INSERT... SELECT) inserts to an existing table.

In versions of SQL Server prior to 2008 the first one could be minimally logged and the second one not but this is no longer true.

like image 42
Martin Smith Avatar answered Sep 21 '22 13:09

Martin Smith