tags:

views:

50

answers:

3

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?

A: 

Why would you not simply run this as two separate queries?

begin transaction
UPDATE Table
SET NewValue = OldValue

UPDATE Table
SET OldValue = NULL
commit

Or is this homework?

Jason Kester
I think Codex asked the wrong question, but I think that egrunin and Thomas answered it.
Marcus Adams
Yes, my question was probably poorly worded. I am doing that right now, but I wondered if I couldn't combine the queries together and just do it all at once. I thought you could, as Egrunin and Thomas elaborated, but I was unsure how I could check that.And no, it's not a homework assignment, it was a question that came up while writing a query for work and I didn't have an answer at the time.
CodexArcanum
+6  A: 

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.

egrunin
No, I wouldn't have thought it unusual, just wasn't at all sure where to look to find an answer on exactly how that would work. Seems like the sort of thing you either learn about when first learning SQL (low level details) or not at all. Thanks to you and Thomas for setting me straight on the matter.
CodexArcanum
+4  A: 

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
Thomas