Received: from localhost (unknown [200.46.204.183]) by mail.postgresql.org (Postfix) with ESMTP id 8CD09634667 for ; Wed, 1 Apr 2009 13:36:06 -0300 (ADT) 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 77649-05 for ; Wed, 1 Apr 2009 13:36:02 -0300 (ADT) X-Greylist: delayed 00:05:33.567675 by SQLgrey-1.7.6 Received: from jimbo.globalnet.hr (jimbo.bnet.hr [213.149.32.23]) by mail.postgresql.org (Postfix) with ESMTP id B143F633FAD for ; Wed, 1 Apr 2009 13:36:02 -0300 (ADT) Received: from mail.globalnet.hr (cartman.globalnet.hr [213.149.32.10]) by jimbo.globalnet.hr (Postfix) with ESMTP id 2CE482D7C6E for ; Wed, 1 Apr 2009 18:30:26 +0200 (CEST) Received: (qmail 3226 invoked from network); 1 Apr 2009 16:30:26 -0000 X-Mail-Scanner: Scanned by qSheff-II-2.1-r2 (http://www.enderunix.org/qsheff/) Received: from dh207-116-254.xnet.hr (HELO [88.207.116.254]) ([88.207.116.254]) (envelope-sender ) by 0 (qmail-ldap-1.03) with SMTP for ; 1 Apr 2009 16:30:26 -0000 Message-ID: <49D3969F.4030701@zg.htnet.hr> Date: Wed, 01 Apr 2009 18:30:23 +0200 From: Rikard Pavelic User-Agent: Thunderbird 2.0.0.21 (Windows/20090302) MIME-Version: 1.0 To: pgsql-performance@postgresql.org Subject: self join revisited Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit X-Virus-Scanned: Maia Mailguard 1.0.1 X-Archive-Number: 200904/10 X-Sequence-Number: 33377 How hard would it be to teach planer to optimize self join? While this query which demonstrates it is not that common SELECT count(*) FROM big_table a INNER JOIN big_table b ON a.id = b.id; This type of query (self joining large table) is very common (at least in our environment because of heavy usage of views). It would be great if Postgres could rewrite this query SELECT bt1.id, bt1.total, sq.id, sq.total FROM big_table bt1 INNER JOIN small_table st1 on st1.big_id = bt1.id INNER JOIN ( SELECT bt2.id, st2.total FROM big_table bt2 INNER JOIN small_table st2 on st2.big_id = bt2.id WHERE st2.total > 100 ) sq ON sq.id = bt1.id WHERE st1.total<200 like this SELECT bt1.id, bt1.total, bt1.id, st2.total FROM big_table bt1 INNER JOIN small_table st1 on st1.big_id = bt1.id INNER JOIN small_table st2 on st2.big_id = bt1.id AND st2.total > 100 WHERE st1.total<200 Regards, Rikard