Insert with Transaction Significantly Faster than Individual Inserts - SQL Server

Shervan360 1,601 Reputation points
2021-12-06T14:26:13.723+00:00

Hello,

Could you please explain this? Why insert with Transaction significantly faster than individual inserts in SQL Server?
155334-screenshot-2021-12-06-092322.jpg

155317-screenshot-2021-12-06-092248.jpg

Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,652 questions
{count} votes

Accepted answer
  1. Erland Sommarskog 112.7K Reputation points MVP
    2021-12-06T23:08:02.003+00:00

    Yes, when you have a number INSERT statements like this, it's definitely a go-faster button to wrap a transaction around them.

    Without a transaction, each INSERT is its own transaction. This means that SQL Server has to wait for the log record for the insert to be written to disk, so that the INSERT can be rolled forward if the server crashes and must restart.

    This is not needed when there is a transaction, because if the server crashes the transaction will be rolled back. Therefore SQL Server can move on to the next statement, and the the log record can be written asynchronously in the background. Only a COMMIT TRANSACTION, SQL Server has to wait.

    Although, if you are inserting an insane number of rows, let's say many millions, it may be slower with a single transaction. The best may be to commit after each 1000 rows or so.

    2 people found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Olaf Helper 45,096 Reputation points
    2021-12-06T20:41:46.433+00:00

    Why insert with Transaction significantly faster than individual inserts in SQL Server?

    May be temporary blocking by other processes?
    Sorry, but that' really to less on information, please provide more details.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.