Received: from magus.postgresql.org ([87.238.57.229]) by malur.postgresql.org with esmtp (Exim 4.72) (envelope-from ) id 1THykU-0008Ci-Ec for pgsql-sql@postgresql.org; Sat, 29 Sep 2012 15:14:34 +0000 Received: from mailout02.ims-firmen.de ([213.174.32.97]) by magus.postgresql.org with esmtp (Exim 4.72) (envelope-from ) id 1THykS-0007NS-Bp for pgsql-sql@postgresql.org; Sat, 29 Sep 2012 15:14:34 +0000 Received: from mailin01.ims-firmen.de ([192.168.1.141]) by mailout02.ims-firmen.de with esmtp (envelope-from ) id 1THykQ-0007Qv-lQ; Sat, 29 Sep 2012 17:14:30 +0200 Received: from [213.174.32.192] (helo=oxweb02.ims-firmen.de) by mailin01.ims-firmen.de with esmtpsa (TLSv1:RC4-MD5:128) (envelope-from ) id 1THykQ-0007kn-1z; Sat, 29 Sep 2012 17:14:30 +0200 Date: Sat, 29 Sep 2012 17:13:18 +0200 (CEST) From: Andreas Kretschmer Reply-To: Andreas Kretschmer To: Thomas Kellerer , pgsql-sql@postgresql.org Message-ID: <301621609.148693.1348931598720.JavaMail.open-xchange@ox.ims-firmen.de> In-Reply-To: References: <43516431.HfO3TYfNBy@hek506> Subject: Re: Reuse temporary calculation results in an SQL update query MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 7bit X-Priority: 3 Importance: Medium X-Mailer: Open-Xchange Mailer v6.20.6-Rev4 X-Pg-Spam-Score: -1.9 (-) X-Archive-Number: 201209/62 X-Sequence-Number: 36864 Thomas Kellerer hat am 29. September 2012 um 16:13 geschrieben: > 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 Yeah, with a WITH - CTE, cool ;-) Andreas