From: | Condor <condor(at)stz-bg(dot)com> |
---|---|
To: | <pgsql-general(at)postgresql(dot)org> |
Subject: | Re: Need advice to avoid ORDER BY |
Date: | 2013-04-04 21:49:40 |
Message-ID: | a71905932a20d7aff84d66058b245bda@stz-bg.com |
Views: | Raw Message | Whole Thread | Download mbox | Resend email |
Thread: | |
Lists: | pgsql-general |
On 2013-04-05 00:38, Merlin Moncure wrote:
> On Thu, Apr 4, 2013 at 4:32 PM, Condor <condor(at)stz-bg(dot)com> wrote:
>> Hello,
>>
>> I have one query in my postgresql 9.2.3 that took 137 ms to me
>> executed and
>> looking a way
>> what I can do to optimize it. I have one table generated numbers from
>> 1 to 1
>> 000 000 and
>> I need to get first free id, meanwhile id's when is taken can be free
>> (deleted data and id
>> is free for next job). Table is simple:
>>
>>
>> id serial,
>> jobid text,
>> valids int default 0
>>
>> (Yes, I have index).
>>
>>
>> my query is: SELECT jobid FROM mytable WHERE valids = 0 ORDER BY id
>> ASC
>> LIMIT 1
>>
>> I need the first id only.
>>
>> My question is: Is there a way how I can avoid using ORDER BY to
>> receive the
>> first
>> free id from mytable ?
>
> well, you can (via EXISTS()), but you can really optimize this with
> partial index.
>
> CREATE INDEX ON mytable (id) WHERE valids = 0;
>
> then,
>
> 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.
Why, your solution is worked ? Yes, it's worked.
Cheers,
Condor
From | Date | Subject | |
---|---|---|---|
Next Message | Merlin Moncure | 2013-04-04 21:58:49 | Re: Need advice to avoid ORDER BY |
Previous Message | Merlin Moncure | 2013-04-04 21:38:07 | Re: Need advice to avoid ORDER BY |