Re: Appending to an array

From: Joe Conway <mail(at)joeconway(dot)com>
To: Jay O'Connor <joconnor(at)cybermesa(dot)com>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: Appending to an array
Date: 2003-04-15 16:57:30
Message-ID: 3E9C39FA.8050601@joeconway.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Jay O'Connor wrote:
> I've got a tablewhere one of the columns contains an array. What I'm
> trying to do is to append or insert into the array. I know I can so
> something like..
> UPDATE mytable set myarray[10] = 'some value' WHERE...
>
> ..to change a particular array element, and this be used to extend the
> array if the array is not that size yet, but what I need to figure out is
> how to do that when I don't know the size of the array at any given time.
>

How's this? (requires version 7.3.x)

CREATE OR REPLACE FUNCTION array_next(text[]) returns int AS '
DECLARE
arr alias for $1;
high int;
BEGIN
high := 1 +
replace(split_part(array_dims(arr),'':'',2),'']'','''')::int;
RETURN high;
END;
' LANGUAGE 'plpgsql' IMMUTABLE STRICT;

create table mytable (myarray text[]);
insert into mytable values ('{"abc","d e f"}');
update mytable set myarray[array_next(myarray)] = 'new element';
regression=# select * from mytable;
myarray
-----------------------------
{abc,"d e f","new element"}
(1 row)

HTH,

Joe

In response to

Browse pgsql-general by date

  From Date Subject
Next Message John Liu 2003-04-15 17:21:15 Re: Are we losing momentum?
Previous Message Bruce Momjian 2003-04-15 16:55:38 Re: Are we losing momentum?