Re: count(*), EXISTS, indexes

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Itai Zukerman <zukerman(at)math-hat(dot)com>
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: count(*), EXISTS, indexes
Date: 2003-04-11 21:10:52
Message-ID: 13918.1050095452@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Itai Zukerman <zukerman(at)math-hat(dot)com> 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

In response to

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Itai Zukerman 2003-04-11 21:22:33 Re: count(*), EXISTS, indexes
Previous Message Itai Zukerman 2003-04-11 21:06:25 Re: count(*), EXISTS, indexes