Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Transactions Always Atomic?

I'm trying to better understand a nuance of SQL Server transactions.

Say I have a query that updates 1,000 existing rows, updating one of the columns to have the values 1 through 1,000. It's possible to execute this query and, when completed, those rows would not be numbered sequentially. This is because it's possible for another query to modify one of those rows before my query finishes.

On the other hand, if I wrap those updates in a transaction, that guarantees that if any one update fails, I can fail all updates. But does it also mean that those rows would be guaranteed to be sequential when I'm done?

In other words, are transactions always atomic?

like image 635
Jonathan Wood Avatar asked Dec 12 '22 11:12

Jonathan Wood


1 Answers

But does it also mean that those rows would be guaranteed to be sequential when I'm done?

No. This has nothing to do with transactions, because what you're asking for simply doesn't exists: relational tables have no order an asking for 'sequential rows' is the wrong question to ask. You can rephrase the question as 'will the 1000 updated rows contain the entire sequence from 1 to 1000, w/o gaps' ? Most likely yes, but the truth of the matter is that there could be gaps depending on the way you do the updates. Those gaps would not appear because updated rows are modified after the update before commit, but because the update will be a no-op (will not update any row) which is a common problem of read-modify-write back type of updates ( the row 'vanishes' between the read and the write-back due to concurrent operations).

To answer your question more precisely whether your code is correct or not you have to post the exact code you're doing the update with, as well as the exact table structure, including all indexes.

like image 63
Remus Rusanu Avatar answered Dec 31 '22 13:12

Remus Rusanu