X-Original-To: pgsql-sql@postgresql.org Received: from spampd.localdomain (postgresql.org [64.49.215.8]) by postgresql.org (Postfix) with ESMTP id 8E5CF475F1B for ; Fri, 11 Apr 2003 16:39:49 -0400 (EDT) Received: from nycsmtp5out-eri0.rdc-nyc.rr.com (nycsmtp5out-eri0.rdc-nyc.rr.com [24.29.99.228]) by postgresql.org (Postfix) with ESMTP id 9A165475EDF for ; Fri, 11 Apr 2003 16:39:48 -0400 (EDT) Received: from math-hat.com (66-65-68-41.nyc.rr.com [66.65.68.41]) by nycsmtp5out-eri0.rdc-nyc.rr.com (8.12.1/Road Runner SMTP Server 1.0) with SMTP id h3BKU1wL003596 for ; Fri, 11 Apr 2003 16:30:01 -0400 (EDT) Received: (nullmailer pid 23134 invoked by uid 1000); Fri, 11 Apr 2003 20:39:49 -0000 To: pgsql-sql@postgresql.org Subject: count(*), EXISTS, indexes From: Itai Zukerman Date: Fri, 11 Apr 2003 16:39:49 -0400 Message-ID: <874r54sr8q.fsf@matt.w80.math-hat.com> User-Agent: Gnus/5.090018 (Oort Gnus v0.18) Emacs/21.2 (gnu/linux) MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii X-Spam-Status: No, hits=-12.3 required=5.0 tests=BAYES_01,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/181 X-Sequence-Number: 12882 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. It *will* use the index with: SELECT sum(A.v) FROM A,B WHERE A.x=B.x; ...but that's not the same thing. This is soooo close: SELECT count(DISTINCT A.x) FROM A,B WHERE A.x=B.x; Am I going to have to write a plpgsql function for this? 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. -- Itai Zukerman