Received: from localhost (unknown [200.46.204.183]) by mail.postgresql.org (Postfix) with ESMTP id A8E536501BE for ; Tue, 4 Nov 2008 09:39:58 -0400 (AST) Received: from mail.postgresql.org ([200.46.204.86]) by localhost (mx1.hub.org [200.46.204.183]) (amavisd-maia, port 10024) with ESMTP id 13097-08 for ; Tue, 4 Nov 2008 09:39:58 -0400 (AST) X-Greylist: from auto-whitelisted by SQLgrey-1.7.6 Received: from sss.pgh.pa.us (sss.pgh.pa.us [66.207.139.130]) by mail.postgresql.org (Postfix) with ESMTP id C211D6501C0 for ; Tue, 4 Nov 2008 09:39:57 -0400 (AST) Received: from sss2.sss.pgh.pa.us (tgl@localhost [127.0.0.1]) by sss.pgh.pa.us (8.14.2/8.14.2) with ESMTP id mA4DdWNU016440; Tue, 4 Nov 2008 08:39:32 -0500 (EST) To: Martin Kjeldsen cc: pgsql-performance@postgresql.org Subject: Re: Aggregate weirdness In-reply-to: <20081104105625.GB1383@martinkjeldsen.dk> References: <20081104105625.GB1383@martinkjeldsen.dk> Comments: In-reply-to Martin Kjeldsen message dated "Tue, 04 Nov 2008 11:56:25 +0100" Date: Tue, 04 Nov 2008 08:39:32 -0500 Message-ID: <16439.1225805972@sss.pgh.pa.us> From: Tom Lane X-Archive-Number: 200811/4 X-Sequence-Number: 31735 Martin Kjeldsen writes: > CREATE OR REPLACE VIEW v_test_with_number AS > SELECT > t.*, > (SELECT SUM(number) FROM test_use WHERE test_id = t.id) as numbers > FROM test t; This is a bad way to do it --- the sub-select isn't readily optimizable. Try something like SELECT t.id, t.name, sum(test_use.number) AS numbers FROM test_use JOIN test t ON test_use.test_id = t.id GROUP BY t.id, t.name; regards, tom lane