Imran
Imran

Reputation: 1902

Do I really need a database transaction?

Is there a point in creating a transaction if my method has several read and only update, delete statement? Although, in the surface it does not make any sense (if it was single threaded); but this is a concurrent web application where multiple threads may modify data simultaneously.

Upvotes: 0

Views: 342

Answers (3)

Fred Woolard
Fred Woolard

Reputation: 161

Yes, possibly there is a good reason to include your read (SELECT) operations within an explicit transaction or unit of work. If the decision to update or delete some row depends on column values from a row (the same row, or a row in another table) that you read, or even the existence of some row, then you might need to do that SELECT as part of a transaction.

A simple example case: Table A contains books, and has a int column for rating. I want to delete a book row if it has a rating of zero (0). Without a transaction, code in the data layer selects rows with a rating of 0, and you then iterate through that collection of book rows. Sometime after you've selected the rows, another user changes the rating of one of the books to one (1). You still end up deleting that book row, when it shouldn't have been.

There are strategies for data consistency, and checking for updates since you've fetched the data (timestamps, etc.), but you just need to evaluate the risk to data integrity when you read data and make decisions from that data, and you allow updates by other users to that same data.

Transactions are meant to eliminate that risk.

Upvotes: 1

A1m
A1m

Reputation: 3107

If this method does for example 2 reads after another and there is another method that is updating your database. It could happen, that one read happens, then your other (transactional) method runs concurrently, and only after that your second reads gets executed. This may lead to an invalid read result.

Upvotes: 1

Ali Faris
Ali Faris

Reputation: 18592

if you have more than one database operation (INSERT , UPDATE , DELETE) in the method there will be point to use transection

Upvotes: 1

Related Questions