Re: Speed of exist

From: Pavel Stehule <pavel(dot)stehule(at)gmail(dot)com>
To: Bastiaan Olij <bastiaan(at)basenlily(dot)me>
Cc: pgsql-performance(at)postgresql(dot)org
Subject: Re: Speed of exist
Date: 2013-02-19 07:39:31
Message-ID: CAFj8pRAUp0SNc5Ur-aYaUpDUXjjRPxC0TozRPwGZ3v4fZFEEqA@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-performance

2013/2/19 Bastiaan Olij <bastiaan(at)basenlily(dot)me>:
> Hi Andy,
>
> I've tried that with the same result. One subquery works beautifully,
> two subqueries with an OR and it starts to do a sequential scan...

try to rewrite OR to two SELECTs joined by UNION ALL

Pavel

>
> Thanks,
>
> Bastiaan Olij
>
> On 19/02/13 6:31 PM, Andy wrote:
>> Limit the sub-queries to 1, i.e. :
>>
>> select 1 from Table2 where Table2.ForeignKey = Table1.PrimaryKey fetch
>> first 1 rows only
>>
>> Andy.
>>
>> On 19.02.2013 07:34, Bastiaan Olij wrote:
>>> 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
>>>
>>>
>>>
>>
>
>
>
> --
> Sent via pgsql-performance mailing list (pgsql-performance(at)postgresql(dot)org)
> To make changes to your subscription:
> http://www.postgresql.org/mailpref/pgsql-performance

In response to

Responses

Browse pgsql-performance by date

  From Date Subject
Next Message Tom Lane 2013-02-19 10:09:42 Re: slow query plans caused by under-estimation of CTE cardinality
Previous Message Bastiaan Olij 2013-02-19 07:36:48 Re: Speed of exist