Speed of exist

From: Bastiaan Olij <bastiaan(at)basenlily(dot)me>
To: Postgres performance mailing list <pgsql-performance(at)postgresql(dot)org>
Subject: Speed of exist
Date: 2013-02-19 06:34:56
Message-ID: 51231D10.1070101@basenlily.me
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-performance

Hi All,

Hope someone can help me a little bit here:

I've got a query like the following:
--
select Column1, Column2, Column3
from Table1
where exists (select 1 from Table2 where Table2.ForeignKey =
Table1.PrimaryKey)
or exists (select 1 from Table3 where Table3.ForeignKey = Table1.PrimaryKey)
--

Looking at the query plan it is doing a sequential scan on both Table2
and Table3.

If I remove one of the subqueries and turn the query into:
--
select Column1, Column2, Column3
from Table1
where exists (select 1 from Table2 where Table2.ForeignKey =
Table1.PrimaryKey)
--

It is nicely doing an index scan on the index that is on Table2.ForeignKey.

As Table2 and Table3 are rather large the first query takes minutes
while the second query takes 18ms.

Is there a way to speed this up or an alternative way of selecting
records from Table1 which have related records in Table2 or Table3 which
is faster?

Kindest Regards,

Bastiaan Olij

Responses

Browse pgsql-performance by date

  From Date Subject
Next Message Andy 2013-02-19 07:31:02 Re: Speed of exist
Previous Message Mark Kirkwood 2013-02-19 04:28:00 Re: High CPU usage / load average after upgrading to Ubuntu 12.04