From: | Vik Fearing <vik(dot)fearing(at)dalibo(dot)com> |
---|---|
To: | gmb <gmbouwer(at)gmail(dot)com> |
Cc: | pgsql-sql(at)postgresql(dot)org |
Subject: | Re: UNNEST result order vs Array data |
Date: | 2013-06-20 12:11:35 |
Message-ID: | 51C2F177.8020808@dalibo.com |
Views: | Raw Message | Whole Thread | Download mbox | Resend email |
Thread: | |
Lists: | pgsql-sql |
On 06/20/2013 01:00 PM, gmb wrote:
> Can you please give me an example of how the order is specified?
> I want the result of the UNNEST to be in the order of the array field
> E.g.
> SELECT UNNEST ( ARRAY[ 'abc' , 'ggh' , '12aa' , '444f' ] );
> Should always return:
>
> unnest
> --------
> abc
> ggh
> 12aa
> 444f
>
> How should the ORDER BY be implemented in the syntax?
There are two ways I can think of right now. The best, which you won't
like, is to wait for 9.4 where unnest() will most likely have a WITH
ORDINALITY option and you can sort on that. The other is to make your
own unnest function that will return the values plus the position. That
would look something like this:
CREATE OR REPLACE FUNCTION unnest_with_ordinality(anyarray, OUT value
anyelement, OUT ordinality integer)
RETURNS SETOF record AS
$$
SELECT $1[i], i FROM
generate_series(array_lower($1,1),
array_upper($1,1)) i;
$$
LANGUAGE sql IMMUTABLE;
and then
select value from unnest_with_ordinality(ARRAY[ 'abc' , 'ggh' , '12aa' ,
'444f']) order by ordinality;
From | Date | Subject | |
---|---|---|---|
Next Message | gmb | 2013-06-20 12:13:14 | Re: UNNEST result order vs Array data |
Previous Message | Richard Huxton | 2013-06-20 11:37:57 | Re: UNNEST result order vs Array data |