Home > Software engineering >  Read Commited and Read Uncommited in microsoft sql server in an example
Read Commited and Read Uncommited in microsoft sql server in an example

Time:08-24

This question is more of a theoretical one.

Let's say that you have the table Employees:

id name salary
1 Stanley 500
2 Jan 600
3 Zaid 700

Let's also say that I have 2 transactions:

T1:

 Begin Transaction
 S1: update Employees set salary = 2*salary where name = ‘Zaid’
 S2: update Employees set salary = 3*salary where name = ‘Zaid’
 Commit;

T2:

 Begin Transaction
 S3: update Employees set salary = salary - 20 where name = ‘Zaid’
 S4: update Employees set salary = salary - 10 where name = ‘Zaid’
 Commit;

Let's also say that T1 is executed with isolation level of "Read Uncommitted" and T2 is executed with isolation level of "Read Committed"

How can will they execute?

My thought process is something like this: @value = the original value of zaid's salary

Time Transaction 1 Transaction 2 Salary (value of the salary at the given time)
0 Begin Transaction @value
1 S1 Begin Transaction 2 * @value
2 S3 @value - 20
3 S2 3*(2*value -20)
4 S4 (@value - 20) - 10
5 Commit; [this is where I think I lost it completely] 3*(2*value -20)
6 Commit; (@value - 20) - 10 ?

As I understand "Read Uncommitted" means that the Transaction 1 will read any changes that will happen on the table from transaction 2, even though they are not committed and "Read Committed" means that the transaction 2 will read only the committed changes from any other transaction. If they are not committed is like they have not happened yet

But how do those two work together? What will happen? Can we know how will they interact? Is the chart I made even remotely accurate?


UPDATE

I just read in Microsoft's web site that:

READ UNCOMMITTED is the least restrictive isolation level because it ignores locks placed by other transactions. Transactions executing under READ UNCOMMITTED can read modified data values that have not yet been committed by other transactions; these are called "dirty" reads.

Does this means that if the 2nd transaction started first, will the first one wait for it to be committed, or will it ignore any exclusive locks that transaction 2 made and place it's own locks?

So it will be something like this:

Time Transaction 1 Transaction 2
0 Begin Transaction
1 Begin Transaction S3
2 S1
3 S2
4 Commit;
5 S4
6 Commit;

CodePudding user response:

Data modifications will take exclusive locks regardless of the isolation level so the UPDATE statement will block when an attempt is made to update an row not yet committed by the other session.

It is also possible a deadlock will occur if the sessions are waiting on each other.

  • Related