Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does ordering matter for fields in a SQL update?

Tags:

sql

sql-server

It occurs to me that if you have fields dependent on each other in an update statement, I'm not sure that one can guarantee the ordering (or that one needs to!).

As an example, say you had the following Update:

UPDATE Table
SET NewValue = OldValue, OldValue = NULL

Would NewValue always update first, then OldValue be nullified? Or is the state of a row (or set, or table, etc) immutable during the processing so that all the changes aren't committed until after the changes have been calculated?

like image 602
CodexArcanum Avatar asked Dec 28 '22 18:12

CodexArcanum


2 Answers

A new virtual row is created, then it replaces the existing row atomically. You have access to all the existing values until the data is committed.

Edit This is not an unusual situation, by the way.

like image 162
egrunin Avatar answered Jan 13 '23 08:01

egrunin


Yes, the system will update NewValue to the value that existed in OldValue prior to the execution of the query and then set OldValue to null. In fact, you can swap values like so:

UPDATE Table
SET NewValue = OldValue, OldValue = NewValue
like image 29
Thomas Avatar answered Jan 13 '23 08:01

Thomas