Re: IN vs EXISTS

From: "Adam Rich" <adam(dot)r(at)sbcglobal(dot)net>
To: "'askel'" <dummy666(at)mail(dot)ru>, <pgsql-general(at)postgresql(dot)org>
Subject: Re: IN vs EXISTS
Date: 2008-06-07 13:59:11
Message-ID: 00a601c8c8a6$a9c27940$fd476bc0$@r@sbcglobal.net
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

> -----Original Message-----
>
> Hi all,
>
> I have been using IN clause almost exclusively until recently I tried
> to use EXISTS and gained significant performance increase without
> changing/creating any indexes:
>
> SELECT ... FROM a WHERE a.ref IN (SELECT b.id WHERE ...)
>
> vs
>
> SELECT ... FROM a WHERE EXISTS (SELECT 1 FROM b WHERE a.ref=b.id ...)
>
> Performance is at least few times better when EXISTS is used. Is it
> just PostgreSQL specific?
>

IN should produce a different query plan than EXISTS. (You can run
"explain analyze" on your queries, to see the different plans).
Which one is faster depends on your data, and on your server. Also,
what's faster on one dbms my be different than another. I've found
that postgresql is usually slower than other databases for IN ()
queries, but handles EXISTS and inner joins (a third way of writing
your queries above) quite quickly.

SELECT a.foo
FROM a
INNER JOIN b on a.ref=b.id

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Viktor Rosenfeld 2008-06-07 14:05:47 temporarily deactivate an index
Previous Message Adam Rich 2008-06-07 13:54:03 Re: hopefully a brain teaser, can't quite figure out query