Re: Sorting by an arbitrary criterion

From: hubert depesz lubaczewski <depesz(at)depesz(dot)com>
To: Craig James <craig_james(at)emolecules(dot)com>
Cc: pgsql-performance(at)postgresql(dot)org
Subject: Re: Sorting by an arbitrary criterion
Date: 2009-07-09 18:11:09
Message-ID: 20090709181109.GB25676@depesz.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-performance

On Thu, Jul 09, 2009 at 09:26:42AM -0700, Craig James wrote:
> Suppose I have a large table with a small-cardinality CATEGORY column (say, categories 1..5). I need to sort by an arbitrary (i.e. user-specified) mapping of CATEGORY, something like this:
>
> 1 => 'z'
> 2 => 'a'
> 3 => 'b'
> 4 => 'w'
> 5 => 'h'
> So when I get done, the sort order should be 2,3,5,4,1.
> I could create a temporary table with the category-to-key mapping, but is there any way to do this in a single SQL statement?

You can do it like this:

select c.*
from categories c, ( values (1, 'z'), (2, 'a'), (3, 'b'), (4, 'w'), (5, 'h') ) as o (id, ordering) on c.id = o.id
order by o.ordering

depesz

--
Linkedin: http://www.linkedin.com/in/depesz / blog: http://www.depesz.com/
jid/gtalk: depesz(at)depesz(dot)com / aim:depeszhdl / skype:depesz_hdl / gg:6749007

In response to

Responses

Browse pgsql-performance by date

  From Date Subject
Next Message Hartman, Matthew 2009-07-09 18:13:52 Re: Sorting by an arbitrary criterion
Previous Message Hartman, Matthew 2009-07-09 17:36:00 Re: Huge difference in query performance between 8.3 and 8.4 (possibly)