Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtp (Exim 4.80) (envelope-from ) id 1UpdiI-0008Dt-MT for pgsql-sql@arkaria.postgresql.org; Thu, 20 Jun 2013 12:11:42 +0000 Received: from localhost ([127.0.0.1] helo=postgresql.org) by malur.postgresql.org with smtp (Exim 4.80) (envelope-from ) id 1UpdiI-0002hA-5F for pgsql-sql@arkaria.postgresql.org; Thu, 20 Jun 2013 12:11:42 +0000 Received: from magus.postgresql.org ([2a02:c0:301:0:ffff::29]) by malur.postgresql.org with esmtp (Exim 4.80) (envelope-from ) id 1UpdiH-0002h1-6U for pgsql-sql@postgresql.org; Thu, 20 Jun 2013 12:11:41 +0000 Received: from mimolette.dalibo.net ([212.85.154.222]) by magus.postgresql.org with esmtp (Exim 4.80) (envelope-from ) id 1UpdiE-0004xs-MP for pgsql-sql@postgresql.org; Thu, 20 Jun 2013 12:11:40 +0000 Received: from [192.168.0.28] (ip-68.net-81-220-133.standre.rev.numericable.fr [81.220.133.68]) by mimolette.dalibo.net (Postfix) with ESMTPSA id 0A6014501AE1; Thu, 20 Jun 2013 14:11:38 +0200 (CEST) Message-ID: <51C2F177.8020808@dalibo.com> Date: Thu, 20 Jun 2013 14:11:35 +0200 From: Vik Fearing User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:17.0) Gecko/20130510 Thunderbird/17.0.6 MIME-Version: 1.0 To: gmb CC: pgsql-sql@postgresql.org Subject: Re: UNNEST result order vs Array data References: <1371724857304-5760087.post@n5.nabble.com> <51C2DD42.4000002@dalibo.com> <1371726033207-5760092.post@n5.nabble.com> In-Reply-To: <1371726033207-5760092.post@n5.nabble.com> Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 7bit X-Pg-Spam-Score: -1.9 (-) List-Archive: List-Help: List-ID: List-Owner: List-Post: List-Subscribe: List-Unsubscribe: X-Mailing-List: pgsql-sql Precedence: bulk Sender: pgsql-sql-owner@postgresql.org 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; -- Sent via pgsql-sql mailing list (pgsql-sql@postgresql.org) To make changes to your subscription: http://www.postgresql.org/mailpref/pgsql-sql