Re: Ordering by IN

From: Eric B(dot)Ridge <ebr(at)tcdi(dot)com>
To: Hadley Willan <hadley(dot)willan(at)deeperdesign(dot)co(dot)nz>
Cc: PGSQL General <pgsql-general(at)postgresql(dot)org>
Subject: Re: Ordering by IN
Date: 2004-08-25 15:07:02
Message-ID: 6B2B61E4-F6A8-11D8-AE5C-000A95BB5944@tcdi.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Aug 25, 2004, at 2:18 AM, Hadley Willan wrote:

> Hi,
>     I was wondering if it's possible to order the result set by some
> of the set contained in an IN clause.
>

I had to do something like this recently. Ended up with a pl/pgsql
function, looked a lot like this:

create or replace function array_find (int8, int8[]) returns int4 as
'declare
data alias for $1;
arr alias for $2;
cnt int4;
begin
cnt := 1;
while arr[cnt] is not null loop
if data = arr[cnt] then
return cnt;
end if;
cnt := cnt + 1;
end loop;

return null;
end;'
language 'plpgsql';

Then, using your original query:

SELECT * FROM v_fol_unit_pub_utmpt
WHERE folder_folder_object = 100120 AND
unit IN ( 90072, 90005, 90074, 90075 ) AND
unit_pub_type IN ( 2 ) AND
utmpt IN ( 1 )
ORDER BY array_find(unit, '{90072, 90005, 90074, 90075}');

Notice that the values are repeated in the ORDER BY clause, in the form
of an array. VeryImportant. Also note that I'm assuming the datatype
of "unit" is an int8... you'll want to adjust the arguments of the
function appropriately for the actual datatype.

With my luck, somebody will respond with a "but postgres already has an
array_find-like function"... but if it does, I couldn't find it.

eric

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Liu, Mingyi 2004-08-25 15:14:36 any solution for full text search in Postgres for partial words
Previous Message Greg Donald 2004-08-25 15:01:22 Re: Gentoo for production DB server?