pg.ddx.io  pgsql-sql@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Thomas F. O'Connell <tfo@monsterlabs.com>
To: pgsql-sql@postgresql.org
Subject: using top-level aggregate values in subqueries
Date: Mon, 23 Apr 2001 19:26:00 -0500
Message-ID: <3AE4C818.5000804@monsterlabs.com> (raw)

from the docs, i know that if you have two tables, foo and bar, you can 
write a query such as

select f.bling
from foo f
where f.id = (
	select max( b.id )
	from bar b
	where b.bling = "i kiss you!"
);

what i'm wondering is if you need that subquery in two places in a query 
if there's some way to cache it at the top level.

for instance, if i were shooting for

select f.id
from foo f, ola o
where f.id = (
	select max( b.id )
	from bar b
	where b.bling = "i kiss you!"
)
and o.id != (
	select max( b.id )
	from bar b
	where b.bling = "i kiss you!"
)

is there some way to grab the value returned by the subquery in the 
superquery and use the value instead of running the subquery twice?

i'm not looking for an optimized version of my example (unless it 
answers the question of the bigger picture); i'd rather know if there's 
some way to access top-level aggregates from within a subquery.

or find out that postgres is smart enough to recognize bits of SQL in a 
query that are identical and do its own internal caching.

generically stated, my question is:

is there some way, without writing a function, to calculate an aggregate 
value in a query that is used in multiple subqueries without needing to 
run an aggregating query multiple times?

i know it only amounts to syntactic sugar, but, as such, it would be 
pretty sweet.

thanks.

-tfo




view thread (3+ messages)  latest in thread

Message-ID: <3AE4C818.5000804@monsterlabs.com>
Permalink:  ../3AE4C818.5000804@monsterlabs.com/
Also on:    postgresql.org/message-id/3AE4C818.5000804@monsterlabs.com

 · 

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 from your mail client; the link fills in
  the headers below: reply via email
  Some clients, webmail especially, drop In-Reply-To and References from
  a link, and the reply then starts a new thread: use the mbox below.

  To: pgsql-sql@postgresql.org
  Cc: tfo@monsterlabs.com
  Subject: Re: using top-level aggregate values in subqueries
  In-Reply-To: <3AE4C818.5000804@monsterlabs.com>
  References: <3AE4C818.5000804@monsterlabs.com>

* 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