pg.ddx.io  pgsql-sql@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Jasen Betts <jasen@xnet.co.nz>
To: pgsql-sql@postgresql.org
Subject: Re: Reuse temporary calculation results in an SQL update query
Date: 29 Sep 2012 11:20:04 GMT
Message-ID: <k46lh4$b08$1@reversiblemaps.ath.cx> (raw)
References: <43516431.HfO3TYfNBy@hek506>

On 2012-09-29, Matthias Nagel <matthias.h.nagel@gmail.com> 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





view thread (10+ messages)  latest in thread

Message-ID: <k46lh4$b08$1@reversiblemaps.ath.cx>
Permalink:  ../k46lh4$b08$1@reversiblemaps.ath.cx/
Also on:    postgresql.org/message-id/k46lh4$b08$1@reversiblemaps.ath.cx

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients using the --to and --cc options:
  reply via email

  To: pgsql-sql@postgresql.org
  Cc: jasen@xnet.co.nz
  Subject: Re: Reuse temporary calculation results in an SQL update query
  In-Reply-To: <k46lh4$b08$1@reversiblemaps.ath.cx>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox