What is the difference between using
SELECT ... INTO MyTable FROM...
and
INSERT INTO MyTable (...)
SELECT ... FROM ....
?
From BOL [ INSERT, SELECT…INTO ], I know that using SELECT…INTO will create the insertion table on the default file group if it doesn’t already exist, and that the logging for this statement depends on the recovery model of the database.
- Which statement is preferable?
- Are there other performance implications?
- What is a good use case for SELECT…INTO over INSERT INTO …?
Edit: I already stated that I know that that SELECT INTO… creates a table where it doesn’t exist. What I want to know is that SQL includes this statement for a reason, what is it? Is it doing something different behind the scenes for inserting rows, or is it just syntactic sugar on top of a CREATE TABLE and INSERT INTO.
They do different things. Use
INSERTwhen the table exists. UseSELECT INTOwhen it does not.Yes.
INSERTwith no table hints is normally logged.SELECT INTOis minimally logged assuming proper trace flags are set.In my experience
SELECT INTOis most commonly used with intermediate data sets, like#temptables, or to copy out an entire table like for a backup.INSERT INTOis used when you insert into an existing table with a known structure.EDIT
To address your edit, they do different things. If you are making a table and want to define the structure use
CREATE TABLEandINSERT. Example of an issue that can be created: You have a small table with a varchar field. The largest string in your table now is 12 bytes. Your real data set will need up to 200 bytes. If you doSELECT INTOfrom your small table to make a new one, the laterINSERTwill fail with a truncation error because your fields are too small.