Received: from makus.postgresql.org ([98.129.198.125]) by malur.postgresql.org with esmtp (Exim 4.72) (envelope-from ) id 1THxo1-0001Ei-UZ for pgsql-sql@postgresql.org; Sat, 29 Sep 2012 14:14:10 +0000 Received: from plane.gmane.org ([80.91.229.3]) by makus.postgresql.org with esmtp (Exim 4.72) (envelope-from ) id 1THxo0-0001bD-9a for pgsql-sql@postgresql.org; Sat, 29 Sep 2012 14:14:09 +0000 Received: from list by plane.gmane.org with local (Exim 4.69) (envelope-from ) id 1THxo0-0005Yr-4F for pgsql-sql@postgresql.org; Sat, 29 Sep 2012 16:14:08 +0200 Received: from host-188-174-151-173.customer.m-online.net ([188.174.151.173]) by main.gmane.org with esmtp (Gmexim 0.1 (Debian)) id 1AlnuQ-0007hv-00 for ; Sat, 29 Sep 2012 16:14:08 +0200 Received: from spam_eater by host-188-174-151-173.customer.m-online.net with local (Gmexim 0.1 (Debian)) id 1AlnuQ-0007hv-00 for ; Sat, 29 Sep 2012 16:14:08 +0200 X-Injected-Via-Gmane: http://gmane.org/ To: pgsql-sql@postgresql.org From: Thomas Kellerer Subject: Re: Reuse temporary calculation results in an SQL update query Date: Sat, 29 Sep 2012 16:13:59 +0200 Lines: 33 Message-ID: References: <43516431.HfO3TYfNBy@hek506> Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit X-Complaints-To: usenet@ger.gmane.org X-Gmane-NNTP-Posting-Host: host-188-174-151-173.customer.m-online.net User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.8.1.21) Gecko/20090302 Thunderbird/2.0.0.21 Mnenhy/0.7.5.666 In-Reply-To: <43516431.HfO3TYfNBy@hek506> X-Pg-Spam-Score: -2.7 (--) X-Archive-Number: 201209/61 X-Sequence-Number: 36863 Matthias Nagel wrote on 29.09.2012 12:49: > Hello, > > is there any way how one can store the result of a time-consuming calculation if this result is needed more >than once in an SQL update query? This solution might be PostgreSQL specific and not standard SQL compliant. > Here is an example of what I want: > > UPDATE table1 SET > StartTime = 'time consuming calculation 1', > StopTime = 'time consuming calculation 2', > Duration = 'time consuming calculation 2' - 'time consuming calculation 1' > WHERE foo; > > It would be nice, if I could use the "new" start and stop time to calculate the duration time. >First of all it would make the SQL statement faster and secondly much more cleaner and easily to understand. Something like: with my_calc as ( select pk, time_consuming_calculation_1 as calc1, time_consuming_calculation_2 as calc2 from foo ) update foo set startTime = my_calc.calc1, stopTime = my_calc.calc2, duration = my_calc.calc2 - calc1 where foo.pk = my_calc.pk; http://www.postgresql.org/docs/current/static/queries-with.html#QUERIES-WITH-MODIFYING