Re: reducing number of ANDs speeds up query

From: Tony Theodore <tony(dot)theodore(at)gmail(dot)com>
To: T(dot) E(dot) Lawrence <t(dot)e(dot)lawrence(at)icloud(dot)com>
Cc: "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 12:47:19
Message-ID: 4C1A40C3-7031-4E9F-A8B1-B9F26BDDE387@gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general


On 12/01/2013, at 12:47 PM, T. E. Lawrence <t(dot)e(dot)lawrence(at)icloud(dot)com> 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?

Have you looked at the WITH clause [1,2]:

WITH filtered as (SELECT table_a.id, b.value as val FROM table_a a, table_b b WHERE … AND …)
SELECT * FROM filtered WHERE filtered.val=…

It evaluates the the first SELECT once, then applies the second SELECT to the first in memory (at least that's the way I think about them).

Cheers,

Tony

[1] http://www.postgresql.org/docs/9.2/static/queries-with.html
[2] http://www.postgresql.org/docs/9.2/static/sql-select.html#SQL-WITH

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Alban Hertroys 2013-01-12 14:34:04 Re: reducing number of ANDs speeds up query
Previous Message T. E. Lawrence 2013-01-12 11:50:54 Re: reducing number of ANDs speeds up query