What does a transaction around a single statement do?

SqlSql ServerTransactions

Sql Problem Overview


I understand how a transaction might be useful for co-ordinating a pair of updates. What I don't understand is wrapping single statements in transactions, which is 90% of what I've ever seen. In fact, in real life code it is more common in my experience to find a series of logically related transactions each wrapped in their own transaction, but the whole is not wrapped in a transaction.

In MS-SQL, is there any benefit from wrapping single selects, single updates, single inserts or single deletes in a transaction?

I suspect this is superstitious programming.

Sql Solutions


Solution 1 - Sql

It does nothing. All individual SQL Statements, (with rare exceptions like Bulk Inserts with No Log, or Truncate Table) are automaticaly "In a Transaction" whether you explicitly say so or not.. (even if they insert, update, or delete millions of rows).

EDIT: based on @Phillip's comment below... In current versions of SQL Server, Even Bulk Inserts and Truncate Table do write some data to the transaction log, although not as much as other operations do. The critical distinction from a transactional perspective, is that in these other types of operations, the data in your database tables being modified is not in the log in a state that allows it to be rolled back.

All this means is that the changes the statement makes to data in the database are logged to the transaction log so that they can be undone if the operation fails.

The only function that the "Begin Transaction", "Commit Transaction" and "RollBack Transaction" commands provide is to allow you to put two or more individual SQL statements into the same transaction.

EDIT: (to reinforce marks comment...) YES, this could be attributed to "superstitious" programming, or it could be an indication of a fundamental misunderstanding of the nature of database transactions. A more charitable interpretation is that it is simply the result of an over-application of consistency which is inappropriate and yet another example of Emersons euphemism that:

A foolish consistency is the hobgoblin of little minds,
adored by little statesmen and philosophers and divines

Solution 2 - Sql

As Charles Bretana said, "it does nothing" -- nothing in addition to what is already done.

Ever hear of the "ACID" requirements of a relational database? That "A" stands for Atomic, meaning that either the statement works in its entirety, or it doesn't--and while the statement is being performed, no other queries can be done on the data affected by that query. BEGIN TRANSACTION / COMMIT "extends" this locking functionality to the work done by multiple statements, but it adds nothing to single statements.

However, the database transaction log is always written to when a database is modified (insert, update, delete). This is not an option, a fact that tends to irritate people. Yes, there's wierdness with bulk inserts and recovery modes, but it still gets written to.

I'll name-drop isolation levels here too. Fussing with this will impact individual commands, but doing so will still not make a declared-transaction-wrapped query perform any differently than a "stand-alone" query. (Note that they can be very powerful and very dangeroug with multi-statement declared transactions.) Note also that "nolock" does not apply to inserts/updates/deletes -- those actions always required locks.

Solution 3 - Sql

For me, wrapping a single statement in a transaction means that I have the ability to roll it back if I, say, forget a WHERE clause when executing a manual, one-time UPDATE statement. It has saved me a few times.

e.g.

--------------------------------------------------------------
CREATE TABLE T1(CPK INT IDENTITY(1,1) NOT NULL, Col1 int, Col2 char(3));
INSERT INTO T1 VALUES (101, 'abc');
INSERT INTO T1 VALUES (101, 'abc');
INSERT INTO T1 VALUES (101, 'abc');
INSERT INTO T1 VALUES (101, 'abc');
INSERT INTO T1 VALUES (101, 'abc');
INSERT INTO T1 VALUES (101, 'abc');
INSERT INTO T1 VALUES (101, 'abc');

SELECT * FROM T1


--------------------------------------------------------------
/* MISTAKE SCENARIO		(run each row individually)	*/
--------------------------------------------------------------
BEGIN TRAN YOUR_TRANS_NAME_1;	/* open a trans named YOUR_TRANS_NAME_1 */
	UPDATE T1 SET COL2 = NULL;	/* run some update statement */
	SELECT * FROM T1;		/* OOPS ... forgot the where clause */
ROLLBACK TRAN YOUR_TRANS_NAME_1;	/* since it did bad things, roll it back */
	SELECT * FROM T1;		/* tans rolled back, data restored. */



--------------------------------------------------------------
/* NO MISTAKES SCENARIO	(run each row individually)	*/
--------------------------------------------------------------

BEGIN TRAN YOUR_TRANS_NAME_2;
	UPDATE T1 SET COL2 = 'CBA' WHERE CPK = 4;	/* run some update statement */
	SELECT * FROM T1;				/* did it correctly this time */

COMMIT TRAN YOUR_TRANS_NAME_2			/* commit (close) the trans */
	
--------------------------------------------------------------
	
DROP TABLE T1

--------------------------------------------------------------

Solution 4 - Sql

When you start an explicit transaction and issue a DML, the resources being locked by the statement remain locked, and the results of statement are not visible from outside the transaction until you manually commit or rollback it.

This is what you may or may not need.

For instance, you may want to show preliminary results to outer world while still keeping a lock on them.

In this case, you start another transaction which places a lock request before the first one commits, thus avoiding race condition

Implicit transactions are commited or rolled back immediatley after the DML statement completes or fails.

Solution 5 - Sql

One possible excuse is that that single statement could cause a bunch of other SQL to run via triggers, and that they're protecting against something going bad in there, although I'd expect any DBMS to have the common sense to use implicit transactions in the same way already.

The other thing I can think of is that some APIs allow you to disable autocommit, and the code's written just in case someone does that.

Solution 6 - Sql

SQL Server has a setting which allows turning autocommit off for a session. It's even the default for some clients (see https://docs.microsoft.com/en-us/sql/t-sql/statements/set-implicit-transactions-transact-sql?view=sql-server-2017)

Depending on a framework and/or a database client you use, not putting each individual command into its own transaction might cause them to be all lumped together into a default transaction. Explicitly wrapping each of them in a transaction clearly declares the intent and actually makes sure it happens the way the programmer intended, regardless of the current autocommit setting, especially if there isn't a company-wide policy on autocommit.

If the begin tran / commit tran commands are being observed in the database (as per your comment [here][1]), it is also possible that a framework is generating them on behalf of an unsuspecting programmer. (How many developers closely inspect SQL code generated by their framework?)

I hope this is still relevant, despite the question being somewhat ancient.

[1]: https://stackoverflow.com/questions/1171749/what-does-a-transaction-around-a-single-statement-do#comment12062517_9521007 "here"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMatthewMartinView Question on Stackoverflow
Solution 1 - SqlCharles BretanaView Answer on Stackoverflow
Solution 2 - SqlPhilip KelleyView Answer on Stackoverflow
Solution 3 - SqlGWRView Answer on Stackoverflow
Solution 4 - SqlQuassnoiView Answer on Stackoverflow
Solution 5 - Sqluser42092View Answer on Stackoverflow
Solution 6 - SqlMartin VajsarView Answer on Stackoverflow