Please consider this sql statements
Create table abc
(A int,
B int
)
insert into abc values (1,2)
Both of the below statements do the same thing. Why?
update abc
set A = B,
B =0
where A=1
and
update abc
set B =0,
A = B
where A=1
I was thinking that in the later statement B columns value is set first and then A columns’ value is set to B's value
No. Single update statements are atomic and there is no order in their individual parts.
Both of these:
do exactly the same thing because the two assignments are considered to happen concurrently.
In other words,
Bon the right side of=is the old value ofB.Addendum: How a DBMS implements this behaviour depends on the cleverness of those writing the DBMS.
For example a DBMS might attempt to lock all the rows where
Ais 1 then, once that’s done, go through and executeA = B,B = 0(in that order because the execution engine deems that will satisfy concurrency, settingAtoBbefore changingB) on each of those rows.A statement like
set A = B, B = Awould require somewhat more intelligence but it could do that easily enough by saving the current row first and using values there to set values in the new row, something like:Then it will unlock all the rows.
That’s just one option. A very dumb DBMS may just lock the entire database file although that wouldn’t make for very intelligent concurrency.
A single-user, single-thread DBMS doesn’t have to care about concurrency at all. It would lock absolutely nothing, just going through each relevant row, making the changes.