Re: selecting data from subquery in same order

From: "Dmitry Koterov" <dmitry(at)koterov(dot)ru>
To: mark <markkicks(at)gmail(dot)com>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: selecting data from subquery in same order
Date: 2008-08-17 12:49:45
Message-ID: d7df81620808170549i1e97af0aob93ec43c76bbd2c8@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

You may use something like this in a stored function:

DECLARE
a INTEGER[];
BEGIN
a := '{2341548, 2325251, 2333130, 2015421,2073536, 2252374, 2273219,
2350850, 2367318, 2032977, 2032849}';
select * from users where id = any(a) order by idx(a, id);
END;

Or in the plain SQL:

select * from users where id = any(a) order by idx('{2341548, 2325251,
2333130, 2015421,2073536, 2252374, 2273219, 2350850, 2367318, 2032977,
2032849}', id);

Note that it is pretty fast only if the array contains not too much elements
(e.g. 20). Do not use for large arrays!

On Sun, Aug 17, 2008 at 4:11 AM, mark <markkicks(at)gmail(dot)com> wrote:

> hi
> if i execute this statement:
>
> select * from users where id in (2341548, 2325251, 2333130, 2015421,
> 2073536, 2252374, 2273219, 2350850, 2367318, 2032977, 2032849, )
>
> the order of rows obtained is random.
>
> is there anyway i can get the rows in the same order as the ids in
> subquery? or is there a different statement i can use?
> thanks!
>
> --
> Sent via pgsql-general mailing list (pgsql-general(at)postgresql(dot)org)
> To make changes to your subscription:
> http://www.postgresql.org/mailpref/pgsql-general
>

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Олег Василенко 2008-08-17 14:02:57 How to execute 'set session role' from plpgsql function?
Previous Message Ivan Sergio Borgonovo 2008-08-17 10:31:28 Re: \copy, transactions and permissions