Re: Need advice to avoid ORDER BY

From: Merlin Moncure <mmoncure(at)gmail(dot)com>
To: Condor <condor(at)stz-bg(dot)com>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: Need advice to avoid ORDER BY
Date: 2013-04-04 21:58:49
Message-ID: CAHyXU0yT0mHR+8YcZ3=j_Wxmfcx_y8QjBWhdv-fqY7xhsmQ0zQ@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Thu, Apr 4, 2013 at 4:49 PM, Condor <condor(at)stz-bg(dot)com> wrote:
>> SELECT jobid FROM mytable WHERE valids = 0 ORDER BY id ASC LIMIT 1;
>>
>> should return in zero time since btree indexes can optimize order by
>> expressions and the partial index will bypass having to wade through
>> the rows you don't want.
>>
>> merlin
>
>
>
> Hm,
> I only can say: Thank You!
> Your solution is work, but Im now a little confused. I has a index
> CREATE INDEX ON mytable (valids) USING BTREE (valids) and the
> query to find valids = 0 tooks 137 ms.

problem is that you are looking for needles (valids = 0) in the
haystack. the problem wasn't really the order, but the fact that you
had to scan an arbitrary amount of rows before finding a candidate
record. so the partial index manages this problem by creating index
entries *only for records that match a criteria*, and the planner
recognizes this and prefers that index when the criteria is also
present in the query. In other words, index only the needles.

merlin

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message John R Pierce 2013-04-04 22:07:41 Re: Need advice to avoid ORDER BY
Previous Message Condor 2013-04-04 21:49:40 Re: Need advice to avoid ORDER BY