pg.ddx.io  pgsql-sql@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Itai Zukerman <zukerman@math-hat.com>
To: Tom Lane <tgl@sss.pgh.pa.us>
Cc: pgsql-sql@postgresql.org
Subject: Re: count(*), EXISTS, indexes
Date: Fri, 11 Apr 2003 17:22:33 -0400
Message-ID: <87vfxkrap2.fsf@matt.w80.math-hat.com> (raw)
In-Reply-To: <13918.1050095452@sss.pgh.pa.us>
References: <874r54sr8q.fsf@matt.w80.math-hat.com>
	<13918.1050095452@sss.pgh.pa.us>

>> 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  <http://www.math-hat.com/~zukerman/;




view thread (14+ messages)  latest in thread

Message-ID: <87vfxkrap2.fsf@matt.w80.math-hat.com>
Permalink:  ../87vfxkrap2.fsf@matt.w80.math-hat.com/
Also on:    postgresql.org/message-id/87vfxkrap2.fsf@matt.w80.math-hat.com

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients using the --to and --cc options:
  reply via email

  To: pgsql-sql@postgresql.org
  Cc: zukerman@math-hat.com, tgl@sss.pgh.pa.us
  Subject: Re: count(*), EXISTS, indexes
  In-Reply-To: <87vfxkrap2.fsf@matt.w80.math-hat.com>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox