I could probably google this, but it seemed quirky enough that it might be worth having logged as an answer on SA.
So in development land, if you want to swap interchance the values of two variables, you need a third temp variable.
e.g.
string x = "ABC";
string y = "DEF";
string temp;
temp = x;
x = y;
y = temp;
However in a SQL Update, you can simply say
UPDATE table
SET ColumnA = ColumnB, ColumnB = ColumnA
How does this work under the hood
- Does SQL Server take a snap shot of the entire row first ?
- Does SQL Server take a snap shot of all the rows being updated in one go ?
- Does the optimizer realize that it’s doing a column interchange, and make a temp variable behind the scenes?
Cheers EoinC
Does SQL Server take a snap shot of the entire row first?
In a way, yes it does.
This is an interesting scenario that highlights the difference between declarative and procedural code. Let us take the following example:
The
UPDATEstatement would work somewhat like this:WHEREclause. All the rows that match theWHEREclause would be marked as a subset. If there were noWHEREclause, then the entire table would have been marked. Using the above example, we could have a subset like the following:user_id | first_name | last_name | age | country ---------+--------------+-------------+-------+--------- 100 | John | Doe | 50 | USAThen a new subset is constructed from the
SETclause. Fields that are not mentioned in theSETclause are copied from the original subset.The
agefield in the new subset will be assigned the value of55directly. The same will happen for thefirst_nameandlast_namefields, but their new assignment values would be retrieved from the original subset. Thecountryfield is copied as-is from the original subset, since it was not mentioned in theSETclause.user_id | first_name | last_name | age | country ---------+--------------+-------------+-------+--------- 100 | Doe | John | 55 | USA