Re: A subselect in an aggregate

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: "Bryan White" <bryan(at)arcamax(dot)com>
Cc: "Ed Loehr" <eloehr(at)austin(dot)rr(dot)com>, "pgsql-sql" <pgsql-sql(at)postgreSQL(dot)org>
Subject: Re: A subselect in an aggregate
Date: 2000-06-26 22:31:46
Message-ID: 19423.962058706@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

"Bryan White" <bryan(at)arcamax(dot)com> writes:
> This is very slow (acutally I killed it after about 5 minutes):
> select o.date,sum(d.qty * d.price) from orderdetail d,orders o where o.date
> = '6/1/2000' group by o.date;

> This is quick (it takes a couple of seconds):
> select o.date,(select sum(od.qty * od.price) from orderdetail od where
> od.orderid = o.orderid) from orders o where o.date = '6/1/2000';

Well, they're not computing the same thing, are they? Since there's no
constraint on d.orderid in the first example, you're asking for the sum
over ALL orderdetail records ... repeated over again for each order
record. For equivalent constraints, I'd expect the first form to be
at least as fast as the second, probably faster.

> Which brings me back to the original question: Is
> there a way to apply an aggregate function to a subselect?

Sure --- you just forgot that a sub-select expression requires its
very own parentheses, so you need two sets:
sum((select ....))
But the other way is probably better...

regards, tom lane

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Gary MacMinn 2000-06-26 23:09:42 Re: Merging two columns into one
Previous Message Bryan White 2000-06-26 19:03:39 Re: A subselect in an aggregate