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

From: Paul Jungwirth <pj(at)illuminatedcomputing(dot)com>
To: Sam Saffron <sam(dot)saffron(at)gmail(dot)com>
Cc: BladeOfLight16 <bladeoflight16(at)gmail(dot)com>, PGSQL Mailing List <pgsql-general(at)postgresql(dot)org>
Subject: Re: How do I bump a row to the front of sort efficiently
Date: 2015-02-04 20:40:36
Message-ID: CA+6hpa=wyA-gbdXv294+i=XmMriwZyhFenKtq-VhoS-A9qJ30A@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general pgsql-hackers

>> I imagine your original would be at risk of LIMITing out the very row you
>> seek to get at the "top", since you don't have an ORDER BY to tell it which
>> ones to keep during the outer LIMIT.

Here is an old thread about combining ORDER BY with UNION:

http://www.postgresql.org/message-id/16814.1280268424@sss.pgh.pa.us

So I think this query would work:

select * from topic
where id = 1000
union all
(select * from topic
where id <> 1000
order by bumped_at desc
limit 29)
order by case when id = 1000 then 0 else 1 end, bumped_at desc
;

> I need to be able to offset and limit the union hack in a view, which
> is proving very tricky.

Since this is sort of a "parameterized view" (which Postgres does not
have) you are probably better off figuring out how to make the UNION
query work with your ORM. What ORM is it? Maybe someone here can help
you with that. Or maybe instead of a view you could write a
set-returning function, e.g. as described here:

http://stackoverflow.com/questions/11401749/pass-in-where-parameters-to-postgresql-view

Paul

--
_________________________________
Pulchritudo splendor veritatis.

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Adam Hooper 2015-02-04 21:26:06 Re: VACUUM FULL pg_largeobject without (much) downtime?
Previous Message Merlin Moncure 2015-02-04 16:25:42 Searching postgres soruces (was: Re: array in a store procedure in C)

Browse pgsql-hackers by date

  From Date Subject
Next Message Peter Eisentraut 2015-02-04 21:21:29 Re: binworld and install-binworld targets - was Re: Release note bloat is getting out of hand
Previous Message Stephen Frost 2015-02-04 20:31:01 Re: Unnecessary pointer-NULL checks in pgp-pgsql.c