Received: from makus.postgresql.org ([98.129.198.125]) by malur.postgresql.org with esmtp (Exim 4.72) (envelope-from ) id 1THvGR-0003Xa-Ui for pgsql-sql@postgresql.org; Sat, 29 Sep 2012 11:31:20 +0000 Received: from plane.gmane.org ([80.91.229.3]) by makus.postgresql.org with esmtp (Exim 4.72) (envelope-from ) id 1THvGO-0007ig-KA for pgsql-sql@postgresql.org; Sat, 29 Sep 2012 11:31:19 +0000 Received: from list by plane.gmane.org with local (Exim 4.69) (envelope-from ) id 1THvGQ-0007Td-FP for pgsql-sql@postgresql.org; Sat, 29 Sep 2012 13:31:18 +0200 Received: from ip-118-90-50-31.xdsl.xnet.co.nz ([118.90.50.31]) by main.gmane.org with esmtp (Gmexim 0.1 (Debian)) id 1AlnuQ-0007hv-00 for ; Sat, 29 Sep 2012 13:31:18 +0200 Received: from jasen by ip-118-90-50-31.xdsl.xnet.co.nz with local (Gmexim 0.1 (Debian)) id 1AlnuQ-0007hv-00 for ; Sat, 29 Sep 2012 13:31:18 +0200 X-Injected-Via-Gmane: http://gmane.org/ To: pgsql-sql@postgresql.org From: Jasen Betts Subject: Re: Reuse temporary calculation results in an SQL update query Date: 29 Sep 2012 11:20:04 GMT Organization: Dis (not Dat) Organisation Lines: 35 Message-ID: References: <43516431.HfO3TYfNBy@hek506> Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit X-Complaints-To: usenet@ger.gmane.org X-Gmane-NNTP-Posting-Host: ip-118-90-50-31.xdsl.xnet.co.nz X-Face: ?)Aw4rXwN5u0~$nqKj`xPz>xHCwgi^q+^?Ri*+R(&uv2=E1Q0Zk(>h!~o2ID@6{uf8s; a +M[5[U[QT7xFN%^gR"=tuJw%TXXR'Fp~W; (T"1(739R%m0Yyyv*gkGoPA.$b,D.w:z+<'"=-lVT?6 {T?=R^:W5g|E2#EhjKCa+nt":4b}dU7GYB*HBxn&Td$@f%.kl^:7X8rQWd[NTc"P"u6nkisze/Q; 8 "9Z{peQF,w)7UjV$c|RO/mQW/NMgWfr5*$-Z%u46"/00mx-,\R'fLPe.)^ User-Agent: slrn/pre1.0.0-18 (Linux) X-Pg-Spam-Score: -2.7 (--) X-Archive-Number: 201210/2 X-Sequence-Number: 36873 On 2012-09-29, Matthias Nagel wrote: > 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. > > Best regards, Matthias use a CTE. http://www.postgresql.org/docs/9.1/static/queries-with.html with a as ( select 'time consuming calculation 1' as tcc1 , 'time consuming calculation 2' as tcc2 ) update table1 SET StartTime = a.tcc1 StopTime = a.tcc2 Duration = a.tcc2 - a.tcc1 WHERE foo; you man need to move foo into the CTE too. -- ⚂⚃ 100% natural