Re: How do I bump a row to the front of sort efficiently

From: David G Johnston <david(dot)g(dot)johnston(at)gmail(dot)com>
To: pgsql-hackers(at)postgresql(dot)org
Subject: Re: How do I bump a row to the front of sort efficiently
Date: 2015-02-02 06:29:29
Message-ID: 1422858569303-5836356.post@n5.nabble.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general pgsql-hackers

sam.saffron wrote
> I have this query:
>
> select * from topics
> order by case when id=1 then 0 else 1 end, bumped_at desc
> limit 30
>
> It works fine, bumps id 1 to the front of the sort fine but is
> terribly inefficient and scans
>
> OTH
>
> "select * from topics where id = 1" is super fast
>
> "select * from topics order by bumped_at desc limit 30" is super fast
>
> Even this is fast, and logically equiv as id is primary key unique
>
> select * from topic
> where id = 1000
> union all
> select * from (
> select * from topics
> where id <> 1000
> order by bumped_at desc
> limit 30
> ) as x
> limit 30
>
>
> However, the contortions on the above query make it very un-ORM
> friendly as I would need to define a view for it but would have no
> clean way to pass limits and offsets in.
>
> Is there any clean technique to bump up particular rows to the front
> of a sort if a certain condition is met without paying a huge
> performance hit?

CREATE FUNCTION ...?

Probably with a VARIADIC argument.

David J.

--
View this message in context: http://postgresql.nabble.com/How-do-I-bump-a-row-to-the-front-of-sort-efficiently-tp5836354p5836356.html
Sent from the PostgreSQL - hackers mailing list archive at Nabble.com.

In response to

Browse pgsql-general by date

  From Date Subject
Next Message hubert depesz lubaczewski 2015-02-02 08:40:56 Re: How do I bump a row to the front of sort efficiently
Previous Message Sam Saffron 2015-02-02 06:16:40 How do I bump a row to the front of sort efficiently

Browse pgsql-hackers by date

  From Date Subject
Next Message Kyotaro HORIGUCHI 2015-02-02 07:27:55 Re: [POC] FETCH limited by bytes.
Previous Message Sam Saffron 2015-02-02 06:16:40 How do I bump a row to the front of sort efficiently