Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Improve INSERT INTO - FROM SELECT, SQL Query

Currently I got this type of query generated by programmation (c#)

INSERT INTO TableName (Field1, Field2, Field3)
SELECT Field1, Field2, Field3 FROM TableName2

The problem is that the SELECT can have a result of many records (like a million), so it's take many times and the result is an connection timeout.

Also, if I separate all the insert into in single insert (for this example, one million insert queries), it's take very long time to execute ... but it work ...

Is there a way I can improve this type of query ?

I use MSSQl 2005

Thx

like image 363
Melursus Avatar asked Feb 12 '09 15:02

Melursus


People also ask

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.

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

I've found out that, if you have a lot of INSERT statements that are executed in sequence, you can improve performance by adding a 'GO' statement after each xxxx number of insert statements:

...
INSERT INTO Table ( ... ) VALUES ( ... )
INSERT INTO Table ( ... ) VALUES ( ... )
INSERT INTO Table ( ... ) VALUES ( ... )
GO
INSERT INTO Table ( ... ) VALUES ( ... )
INSERT INTO Table ( ... ) VALUES ( ... )
...

Another possibility maybe, is to make sure that your INSERT INTO .. SELECT FROM query doesn't insert everything in one time, instead use some kind of paging technique:

INSERT INTO Table ...
SELECT ...
FROM OtherTable WHERE Id > x and Id < y
like image 55
Frederik Gheysels Avatar answered Sep 23 '22 12:09

Frederik Gheysels