X-Original-To: pgsql-sql@postgresql.org Received: from spampd.localdomain (postgresql.org [64.49.215.8]) by postgresql.org (Postfix) with ESMTP id 3AE6F475F1B for ; Fri, 11 Apr 2003 17:10:52 -0400 (EDT) Received: from sss.pgh.pa.us (unknown [192.204.191.242]) by postgresql.org (Postfix) with ESMTP id 99184475EDF for ; Fri, 11 Apr 2003 17:10:51 -0400 (EDT) Received: from sss2.sss.pgh.pa.us (tgl@localhost [127.0.0.1]) by sss.pgh.pa.us (8.12.9/8.12.9) with ESMTP id h3BLAq2L013919; Fri, 11 Apr 2003 17:10:52 -0400 (EDT) To: Itai Zukerman Cc: pgsql-sql@postgresql.org Subject: Re: count(*), EXISTS, indexes In-reply-to: <874r54sr8q.fsf@matt.w80.math-hat.com> References: <874r54sr8q.fsf@matt.w80.math-hat.com> Comments: In-reply-to Itai Zukerman message dated "Fri, 11 Apr 2003 16:39:49 -0400" Date: Fri, 11 Apr 2003 17:10:52 -0400 Message-ID: <13918.1050095452@sss.pgh.pa.us> From: Tom Lane X-Spam-Status: No, hits=-31.7 required=5.0 tests=BAYES_00,EMAIL_ATTRIBUTION,IN_REP_TO,QUOTED_EMAIL_TEXT, REFERENCES,REPLY_WITH_QUOTES,UPPERCASE_25_50 autolearn=ham version=2.50 X-Spam-Level: X-Spam-Checker-Version: SpamAssassin 2.50 (1.173-2003-02-20-exp) X-Archive-Number: 200304/184 X-Sequence-Number: 12885 Itai Zukerman writes: > Define: > CREATE TABLE A (x int PRIMARY KEY, real v); > CREATE TABLE B (x int); > I'd like to calculate: > SELECT sum(v) FROM A WHERE EXISTS (SELECT 1 FROM B WHERE A.x=B.x); > ...but then it won't use the primary key index on A.x. In CVS tip (7.4-to-be) I think SELECT sum(v) FROM A WHERE A.x IN (SELECT B.x FROM B); would probably work well. In current releases I think all you can do is add an index to B.x and settle for the EXISTS() approach. > PS. B is relatively small, a few thousand rows, while A has well over > 500,000 rows. The DISTINCT A.x should be about 10,000-50,000. BTW, how can a PRIMARY KEY column have fewer DISTINCT values than there are rows? regards, tom lane