Co Related query and update
712679Jul 20 2009 — edited Jul 30 2009Hi,
I am using a co related query to update a field in the table across many rows. The outer query of the co related query is an update query. The inner sub query joins with the outer query and returns back the value of the field with some calculations made on it to the outer co related query. The outer one updates this field and then the inner continues processing. The inner picks the same field which was updated by the outer query, as mentioned above.
Here the inner query expects the field to carry the updated value and not the old value which was present prior to the execution of the corelated sub query. But it gets old value in the field.
So my question is, in a corelated update query if certain fields are updated in the query processing then are the values of these not reflected to the db till the whole query is executed. Till this period the updated values are kept in a cache. So if the sub query of the co related query tries to access the field for the updated value during the query processing then it would get the old value.
Following is the query i am using in postgres but my question is in general:
update sample_tab2 a set stock=initialstock + (percent/100)*(select b.stock from sample_tab2 b
where a.region=b.region and b.period=(a.period - cast('1 week' as interval) * 1)) where region='Asia';
Can we do the above in just one query. Thanks.