Received: from localhost (postgresql.org [64.49.215.8]) by postgresql.org (Postfix) with ESMTP id 6AC9B4766F1 for ; Wed, 15 Jan 2003 15:37:54 -0500 (EST) Received: from sss.pgh.pa.us (unknown [192.204.191.242]) by postgresql.org (Postfix) with ESMTP id 074F6476670 for ; Wed, 15 Jan 2003 14:45:21 -0500 (EST) Received: from sss2.sss.pgh.pa.us (tgl@localhost [127.0.0.1]) by sss.pgh.pa.us (8.12.6/8.12.6) with ESMTP id h0FJj75u019506; Wed, 15 Jan 2003 14:45:07 -0500 (EST) To: Tomasz Myrta Cc: pgsql-sql@postgresql.org Subject: Re: sub-select with aggregate In-reply-to: <3DB674CD.50404@klaster.net> References: <3DB674CD.50404@klaster.net> Comments: In-reply-to Tomasz Myrta message dated "Wed, 23 Oct 2002 12:07:09 +0200" Date: Wed, 15 Jan 2003 14:45:06 -0500 Message-ID: <19505.1042659906@sss.pgh.pa.us> From: Tom Lane X-Virus-Scanned: by AMaViS new-20020517 X-Archive-Number: 200301/233 X-Sequence-Number: 11098 [ followup on a gripe from October ] Tomasz Myrta writes: > I want to perform query looking like this: > select > user_id, > a/sum_a as percent_a, > b/sum_b as percent_b > from > users join > (select > group_id, > sum(a) as sum_a, > sum(b) as sum_b > from users group by group_id) X using (group_id) > where group_id=3; > This query works, but very slow. Subquery with aggregate is performed > for all table rows instead of group_id=3. Just FYI, this problem is fixed as of CVS tip. Using an empty table with an index on group_id, I get a plan like so: Nested Loop (cost=17.10..34.21 rows=1 width=36) -> Subquery Scan x (cost=17.10..17.11 rows=1 width=12) -> HashAggregate (cost=17.10..17.11 rows=1 width=12) -> Index Scan using users_group_id on users (cost=0.00..17.07 rows=5 width=12) Index Cond: (3 = group_id) -> Index Scan using users_group_id on users (cost=0.00..17.08 rows=1 width=16) Index Cond: (users.group_id = "outer".group_id) Filter: (group_id = 3) Notice the condition on group_id has been propagated into both sides of the join. regards, tom lane