Imagine the following sql query:
UPDATE MYTABLE SET COL2 = (SELECT COL2 + 1 FROM (SELECT MAX(COL2) FROM MYTABLE) AS X) WHERE ID IN (1,2,3,4,5)
Assume that before the update is executed MAX(COL2) is 1.
My intention is that for the update where ID=1 COL2 is updated to ‘max(COL2) + 1’ (i.e. 2), and that for subsequent updates ‘MAX(COL2) + 1’ is re-evaluated, so that for ID=2, COL2=3 and ID=3, COL2=4 etc…
What actually happens is that for all rows (ID=1,2,3,4,5), the value of COL2 is 2.
Is there a smart way to have the value of MAX(COL2) +1 ‘re-evaluated’ at each update? I realize there may be performance issues with doing this, but I am curious none-the-less! Is there a better alternative (that does not involve multiple update statements) ?
BTW: incase you are wondering about the syntax used for the above query (the nested inner table) see here: SQL : Using the target table in an UPDATE statement in a nested FROM clause
What you encountered here is called
query stability.No query can see the changes made by itself, or the following query:
would never end.