Re: optimizing select ... not in (select ...)

From: Tomas Berndtsson <tomas(at)nocrew(dot)org>
To: Laurent Martelli <laurent(at)aopsys(dot)com>
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: optimizing select ... not in (select ...)
Date: 2001-08-13 14:55:22
Message-ID: 80pua0ypph.fsf@junk.nocrew.org
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Laurent Martelli <laurent(at)aopsys(dot)com> writes:

> I have this query :
>
> select distinct on (Pictures.PictureID) * from Pictures where Pictures.PictureID not in (select distinct PictureID from Keywords);
>
> and I find it a bit slow. Does anybody have suggestions to run this
> faster ? (I have indexes on PictureID on both Pictures and Keywords)

Try this instead:

select distinct on (Pictures.PictureID) *
from Pictures
where not exists (select distinct PictureID from Keywords where Pictures.PictureID=Keywords.PictureID);

I've found that it's usually faster, probably because it can use
indices better.

Tomas

In response to

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Josh Berkus 2001-08-13 15:16:43 Re: optimizing select ... not in (select ...)
Previous Message agutier 2001-08-13 13:43:18 Re: REFERENCES constraint