I have a T-Sql Statement as follows;
Insert into Table1
Select * From Table2
I want to know the running sequence. Does the insert waits select statement to finish before starting or it starts asap select statement starts returning values and expects new records from the select statement to continue.
This is a plain stored procedure and no transactions used.
To echo @CodeByMoonlight’s answer, and to address your comment there: the physical considerations (including the specifics of locking) are always subordinate to the logical instructions specified by the query.
In the processing of an
INSERT ... SELECTstatement, logically speaking theSELECTis carried out to produce a resultset, and then the rows of this resultset areINSERTed. The fact that in this case the source table and the target table are the same table is irrelevant. I’m fairly sure that specifyingNOLOCKorTABLOCKwould in any case apply only to theSELECT, if that’s where you position them.Consider as another example this statement, which makes no sense if you read it in an ‘imperative’ way:
With an imperative, rather than set-based, understanding, this statement might look as if it will result in
Column1andColumn2having the same value for all rows. But it doesn’t – it in fact swaps the values inColumn1andColumn2. Only by understanding that the logical instructions of the query dictate what actually happens can this be seen.