Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if you don't commit a transaction to a database (say, SQL Server)?

Suppose I have a query:

begin tran
-- some other sql code

And then I forget to commit or roll back.

If another client tries to execute a query, what would happen?

like image 402
Charbel Avatar asked Oct 05 '22 16:10

Charbel


People also ask

Why do we need to commit in SQL?

COMMIT in SQL is a transaction control language that is used to permanently save the changes done in the transaction in tables/databases. The database cannot regain its previous state after its execution of commit.

What is the use of commit transaction in SQL Server?

Marks the end of a successful implicit or explicit transaction. If @@TRANCOUNT is 1, COMMIT TRANSACTION makes all data modifications since the start of the transaction a permanent part of the database, frees the transaction's resources, and decrements @@TRANCOUNT to 0.

What would happen if the database transaction log was not present within the database?

If no Transaction Log backup is taken from the database, the Transaction Log file will grow continuously, without truncation, until it runs out of free space.

Is commit required in SQL Server?

The SQL Server Management Studio has implicit commit turned on, so all statements that are executed are implicitly commited. This might be a scary thing if you come from an Oracle background where the default is to not have commands commited automatically, but it's not that much of a problem.


2 Answers

As long as you don't COMMIT or ROLLBACK a transaction, it's still "running" and potentially holding locks.

If your client (application or user) closes the connection to the database before committing, any still running transactions will be rolled back and terminated.

like image 190
marc_s Avatar answered Oct 08 '22 05:10

marc_s


You can actually try this yourself, that should help you get a feel for how this works.

Open a two windows (tabs) in management studio, each of them will have it's own connection to sql.

Now you can begin a transaction in one window, do some stuff like insert/update/delete, but not yet commit. then in the other window you can see how the database looks from outside the transaction. Depending on the isolation level, the table may be locked until the first window is committed, or you might (not) see what the other transaction has done so far, etc.

Play around with the different isolation levels and no lock hint to see how they affect the results.

Also see what happens when you throw an error in the transaction.

It's very important to understand how all this stuff works or you will be stumped by what sql does, many a time.

Have fun! GJ.

like image 45
gjvdkamp Avatar answered Oct 08 '22 05:10

gjvdkamp