X-Original-To: pgsql-sql@postgresql.org Received: from spampd.localdomain (postgresql.org [64.49.215.8]) by postgresql.org (Postfix) with ESMTP id E58D8476344 for ; Fri, 11 Apr 2003 17:22:32 -0400 (EDT) Received: from nycsmtp4out-eri0.rdc-nyc.rr.com (nycsmtp4out-eri0.rdc-nyc.rr.com [24.29.99.227]) by postgresql.org (Postfix) with ESMTP id 3F9C8476340 for ; Fri, 11 Apr 2003 17:22:32 -0400 (EDT) Received: from math-hat.com (66-65-68-41.nyc.rr.com [66.65.68.41]) by nycsmtp4out-eri0.rdc-nyc.rr.com (8.12.1/Road Runner SMTP Server 1.0) with SMTP id h3BLHVYr007488; Fri, 11 Apr 2003 17:17:31 -0400 (EDT) Received: (nullmailer pid 23197 invoked by uid 1000); Fri, 11 Apr 2003 21:22:33 -0000 To: Tom Lane Cc: pgsql-sql@postgresql.org Subject: Re: count(*), EXISTS, indexes Mail-Copies-To: never From: Itai Zukerman Date: Fri, 11 Apr 2003 17:22:33 -0400 In-Reply-To: <13918.1050095452@sss.pgh.pa.us> (Tom Lane's message of "Fri, 11 Apr 2003 17:10:52 -0400") Message-ID: <87vfxkrap2.fsf@matt.w80.math-hat.com> User-Agent: Gnus/5.090018 (Oort Gnus v0.18) Emacs/21.2 (gnu/linux) References: <874r54sr8q.fsf@matt.w80.math-hat.com> <13918.1050095452@sss.pgh.pa.us> MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii X-Spam-Status: No, hits=-31.7 required=5.0 tests=BAYES_01,IN_REP_TO,QUOTED_EMAIL_TEXT,REFERENCES, REPLY_WITH_QUOTES,UPPERCASE_25_50,USER_AGENT_GNUS_UA 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/185 X-Sequence-Number: 12886 >> 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); Oops. I guess I should've changed the example to "WHERE A.x>=B.x" since that's what I'm really doing. Oh, well, my goof. > 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. I don't think indexing B will help speed-wise if it still does the seq scan through A. >> 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? Oh, I just meant, "the DISTINCT A.x that are returned by: SELECT DISTINCT A.x FROM A,B WHERE A.x=B.x ". Sorry for my lack of clarity... -- Itai Zukerman