Re: reducing number of ANDs speeds up query

From: Amit kapila <amit(dot)kapila(at)huawei(dot)com>
To: "T(dot) E(dot) Lawrence" <t(dot)e(dot)lawrence(at)icloud(dot)com>, "pgsql-general(at)postgresql(dot)org" <pgsql-general(at)postgresql(dot)org>
Subject: Re: reducing number of ANDs speeds up query
Date: 2013-01-12 06:10:09
Message-ID: 6C0B27F7206C9E4CA54AE035729E9C383BEB0105@szxeml509-mbs
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general


On Saturday, January 12, 2013 7:17 AM T. E. Lawrence wrote:
> Hello,

> I have a pretty standard query with two tables:

> SELECT table_a.id FROM table_a a, table_b b WHERE ... AND ... AND b.value=...;

> With the last "AND b.value=..." the query is extremely slow (did not wait for it to end, but more than a minute), because the value column is not indexed (contains items longer than 8K).

> However the previous conditions "WHERE ... AND ... AND" should have already reduced the candidate rows to just a few (table_b contains over 50m rows). And indeed, removing the last "AND b.value=..." speeds the query to just a millisecond.

> Is there a way to instruct PostgreSQL to do first the initial "WHERE ... AND ... AND" and then the last "AND b.value=..." on the (very small) result?

You can try once with below query:
Select * from (SELECT a.id,b.value FROM table_a a, table_b b WHERE ... AND ... ) X where X.value=...;

If this doesn't work can you send the Explain .. output for both queries(the query you are using and the query I have suggested)

With Regards,
Amit Kapila.

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Alban Hertroys 2013-01-12 10:47:16 Re: reducing number of ANDs speeds up query
Previous Message pasilveira 2013-01-12 05:31:17 pgadmin connection via tunnel and ubuntu user instead of postgres