Re: Ordering returned rows according to a list

From: Sebastian Tennant <sebyte(at)smolny(dot)plus(dot)com>
To: pgsql-general(at)postgresql(dot)org
Subject: Re: Ordering returned rows according to a list
Date: 2008-12-22 18:02:04
Message-ID: ej00nl5v.fsf@vps203.linuxvps.org
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Quoth "Adam Rich" <adam(dot)r(at)sbcglobal(dot)net>:
>> I'd like to make a single query that returns a number of rows using a
>> 'WHERE id IN (<list-of-ids>)' condition, but I'd like the rows to be
>> returned in the order in which the ids are given in the list.
>>
> Depending on how many IDs you have in your list, you can accomplish this
> with a CASE statement:
>
> SELECT *
> FROM MYTABLE
> WHERE id IN (6, 9, 3)
> ORDER BY CASE id
> WHEN 6 then 1
> WHEN 9 then 2
> WHEN 3 then 3 END

Thanks for this suggestion Adam.

You say "depending on how many IDs there are in the list". The query is
constructed programatically so unless there's a limit on the number of
conditions a CASE clause can handle, this is the way I'll go about it.

Sebastian

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Scott Marlowe 2008-12-22 18:05:33 Re: Erro in vaccum
Previous Message Christophe 2008-12-22 17:34:39 Re: How are locks managed in PG?