From: Tom Lane <tgl@sss.pgh.pa.us>
To: Bryan White <bryan@arcamax.com>
Cc: Ed Loehr <eloehr@austin.rr.com>
Cc: pgsql-sql <pgsql-sql@postgreSQL.org>
Subject: Re: A subselect in an aggregate
Date: Mon, 26 Jun 2000 18:31:46 -0400
Message-ID: <19423.962058706@sss.pgh.pa.us> (raw)
In-Reply-To: <00ad01bfdfa1$3d64ad00$2dd260d1@arcamax.com>
References: <000b01bfdf8c$aef88000$2dd260d1@arcamax.com>
<39578B61.CDAF7D91@austin.rr.com>
<00ad01bfdfa1$3d64ad00$2dd260d1@arcamax.com>
"Bryan White" <bryan@arcamax.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
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: tgl@sss.pgh.pa.us, bryan@arcamax.com, eloehr@austin.rr.com
Subject: Re: A subselect in an aggregate
In-Reply-To: <19423.962058706@sss.pgh.pa.us>
References: <000b01bfdf8c$aef88000$2dd260d1@arcamax.com> <39578B61.CDAF7D91@austin.rr.com> <00ad01bfdfa1$3d64ad00$2dd260d1@arcamax.com> <19423.962058706@sss.pgh.pa.us>
* 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