473,854 Members | 1,512 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

how can I select into an array?

I would like to select strings from a table and return them as an array
For example,
select new_array(name) from my_tbl
would return
String[] { name1, name2, name3, etc }

Is this possible with built-in SQL/psql functions?
If not, how hard would it be to write a function that does this? (given that
I have coding experience but none writing pgsql functions)

Andy Kriger | Software Mechanic | Greater Than One, Inc.
28 West 27th Street | 7th Floor | New York, NY 10001
P: 212.252.7197 | F: 212.252.7364 | E: ak*****@greater thanone.com
Nov 22 '05 #1
8 31271
hello,

try:

CREATE OR REPLACE FUNCTION aggregate_array (ANYARRAY,ANYEL EMENT) RETURNS
ANYARRAY AS '
SELECT
CASE
WHEN $1 IS NULL
THEN ARRAY[$2]
WHEN $2 IS NULL
THEN $1
ELSE array_append($1 ,$2)
END;
' LANGUAGE 'SQL';

CREATE AGGREGATE aggarray (BASETYPE = ANYELEMENT, SFUNC = aggregate_array ,
STYPE = ANYARRAY);

or

CREATE AGGREGATE aggarray (basetype = anyelement, sfunc = array_append,
stype = anyarray, initcond = '{}' );

testdb011=> SELECT count(*), aggarray(prijme ni) FROM lide GROUP BY
prijmeni ~ '.*á';

regards
Pavel Stehule


On Fri, 6 Feb 2004, Andy Kriger wrote:
I would like to select strings from a table and return them as an array
For example,
select new_array(name) from my_tbl
would return
String[] { name1, name2, name3, etc }

Is this possible with built-in SQL/psql functions?
If not, how hard would it be to write a function that does this? (given that
I have coding experience but none writing pgsql functions)

Andy Kriger | Software Mechanic | Greater Than One, Inc.
28 West 27th Street | 7th Floor | New York, NY 10001
P: 212.252.7197 | F: 212.252.7364 | E: ak*****@greater thanone.com

---------------------------(end of broadcast)---------------------------
TIP 3: if posting/reading through Usenet, please send an appropriate
subscribe-nomail command to ma*******@postg resql.org so that your
message can get through to the mailing list cleanly

Nov 22 '05 #2
Thank you for your response - I should have mention I'm using Postgres 7.2.x
ANYARRAY does not appear to exist in that version
Is there a workaround?

-----Original Message-----
From: Pavel Stehule [mailto:st*****@ kix.fsv.cvut.cz]
Sent: Friday, February 06, 2004 10:49 AM
To: Andy Kriger
Cc: Pgsql-General
Subject: Re: [GENERAL] how can I select into an array?

hello,

try:

CREATE OR REPLACE FUNCTION aggregate_array (ANYARRAY,ANYEL EMENT) RETURNS
ANYARRAY AS '
SELECT
CASE
WHEN $1 IS NULL
THEN ARRAY[$2]
WHEN $2 IS NULL
THEN $1
ELSE array_append($1 ,$2)
END;
' LANGUAGE 'SQL';

CREATE AGGREGATE aggarray (BASETYPE = ANYELEMENT, SFUNC = aggregate_array ,
STYPE = ANYARRAY);

or

CREATE AGGREGATE aggarray (basetype = anyelement, sfunc = array_append,
stype = anyarray, initcond = '{}' );

testdb011=> SELECT count(*), aggarray(prijme ni) FROM lide GROUP BY prijmeni
~ '.*á';

regards
Pavel Stehule


On Fri, 6 Feb 2004, Andy Kriger wrote:
I would like to select strings from a table and return them as an
array For example, select new_array(name) from my_tbl would return
String[] { name1, name2, name3, etc }

Is this possible with built-in SQL/psql functions?
If not, how hard would it be to write a function that does this?
(given that I have coding experience but none writing pgsql functions)

Andy Kriger | Software Mechanic | Greater Than One, Inc.
28 West 27th Street | 7th Floor | New York, NY 10001
P: 212.252.7197 | F: 212.252.7364 | E: ak*****@greater thanone.com


---------------------------(end of broadcast)---------------------------
TIP 4: Don't 'kill -9' the postmaster

Nov 22 '05 #3
if you can in plpgsql 7.2.x return array of known type, you can replace
anyarray and anyelement like varchar[], varchar. But I don't know if it
7.2 supported.

Pavel

On Fri, 6 Feb 2004, Andy Kriger wrote:
Thank you for your response - I should have mention I'm using Postgres 7.2.x
ANYARRAY does not appear to exist in that version
Is there a workaround?

-----Original Message-----
From: Pavel Stehule [mailto:st*****@ kix.fsv.cvut.cz]
Sent: Friday, February 06, 2004 10:49 AM
To: Andy Kriger
Cc: Pgsql-General
Subject: Re: [GENERAL] how can I select into an array?

hello,

try:

CREATE OR REPLACE FUNCTION aggregate_array (ANYARRAY,ANYEL EMENT) RETURNS
ANYARRAY AS '
SELECT
CASE
WHEN $1 IS NULL
THEN ARRAY[$2]
WHEN $2 IS NULL
THEN $1
ELSE array_append($1 ,$2)
END;
' LANGUAGE 'SQL';

CREATE AGGREGATE aggarray (BASETYPE = ANYELEMENT, SFUNC = aggregate_array ,
STYPE = ANYARRAY);

or

CREATE AGGREGATE aggarray (basetype = anyelement, sfunc = array_append,
stype = anyarray, initcond = '{}' );

testdb011=> SELECT count(*), aggarray(prijme ni) FROM lide GROUP BY prijmeni
~ '.*á';

regards
Pavel Stehule


On Fri, 6 Feb 2004, Andy Kriger wrote:
I would like to select strings from a table and return them as an
array For example, select new_array(name) from my_tbl would return
String[] { name1, name2, name3, etc }

Is this possible with built-in SQL/psql functions?
If not, how hard would it be to write a function that does this?
(given that I have coding experience but none writing pgsql functions)

Andy Kriger | Software Mechanic | Greater Than One, Inc.
28 West 27th Street | 7th Floor | New York, NY 10001
P: 212.252.7197 | F: 212.252.7364 | E: ak*****@greater thanone.com

---------------------------(end of broadcast)---------------------------
TIP 4: Don't 'kill -9' the postmaster

---------------------------(end of broadcast)---------------------------
TIP 6: Have you searched our list archives?

http://archives.postgresql.org

Nov 22 '05 #4
"Andy Kriger" <ak*****@greate rthanone.com> writes:
I would like to select strings from a table and return them as an array


You can do that beginning in 7.4 with the ARRAY(sub-select) construct.

regression=# select f1 from text_tbl;
f1
-------------------
doh!
hi de ho neighbor
(2 rows)

regression=# select array(select f1 from text_tbl);
?column?
----------------------------
{doh!,"hi de ho neighbor"}
(1 row)

regression=#

In prior versions you could probably fake it with a loop in a plpgsql
function, but it'd be kinda awkward.

regards, tom lane

---------------------------(end of broadcast)---------------------------
TIP 8: explain analyze is your friend

Nov 22 '05 #5
Pavel Stehule wrote:
CREATE AGGREGATE aggarray (BASETYPE = ANYELEMENT, SFUNC = aggregate_array ,
STYPE = ANYARRAY);


Or, from the docs, see:
http://www.postgresql.org/docs/curre...tic/xaggr.html

CREATE AGGREGATE array_accum (
sfunc = array_append,
basetype = anyelement,
stype = anyarray,
initcond = '{}'
);

array_append() is built-in in 7.4 -- and note both Pavel's solution and
this one require 7.4.x

HTH,

Joe

---------------------------(end of broadcast)---------------------------
TIP 3: if posting/reading through Usenet, please send an appropriate
subscribe-nomail command to ma*******@postg resql.org so that your
message can get through to the mailing list cleanly

Nov 22 '05 #6
Pavel Stehule wrote:
if you can in plpgsql 7.2.x return array of known type, you can replace
anyarray and anyelement like varchar[], varchar. But I don't know if it
7.2 supported.


PL/pgSQL array support in anything earlier than 7.4 is pretty weak. I
would strongly recommend upgrading to 7.4 if arrays are important to you.

Joe

---------------------------(end of broadcast)---------------------------
TIP 3: if posting/reading through Usenet, please send an appropriate
subscribe-nomail command to ma*******@postg resql.org so that your
message can get through to the mailing list cleanly

Nov 22 '05 #7
this is a followup to my original message for anyone else stuck on older
psql versions...

i wrote a function to accomplish selecting into an array which works in
7.2.1
you will need to 'createlang plpgsql' (see the docs on procedural languages)
before you can use it
it takes a SQL query as an arg and returns an array aggregated from the
result column named 'arrayval'
it is written to work with varchars but could easily be modified to work
with other data types

-- create an array from the results of a query
-- query must return a column named arrayval
-- $1 = query string
CREATE OR REPLACE FUNCTION array_query(VAR CHAR)
RETURNS VARCHAR[]
AS '
DECLARE
query ALIAS FOR $1;
rec RECORD;
str VARCHAR;
arr VARCHAR[];
BEGIN
str := ''{'';
FOR rec IN EXECUTE query LOOP
str := str || ''"'' || rec.arrayval || ''"'' || '','';
END LOOP;
str := str || ''}'';
SELECT INTO arr str;
RETURN arr;
END;
' LANGUAGE 'plpgsql';
_____

From: pg************* ****@postgresql .org
[mailto:pg****** ***********@pos tgresql.org] On Behalf Of Andy Kriger
Sent: Friday, February 06, 2004 10:37 AM
To: Pgsql-General
Subject: [GENERAL] how can I select into an array?

I would like to select strings from a table and return them as an array
For example,
select new_array(name) from my_tbl
would return
String[] { name1, name2, name3, etc }

Is this possible with built-in SQL/psql functions?
If not, how hard would it be to write a function that does this? (given that
I have coding experience but none writing pgsql functions)

Andy Kriger | Software Mechanic | Greater Than One, Inc.
28 West 27th Street | 7th Floor | New York, NY 10001
P: 212.252.7197 | F: 212.252.7364 | E: ak*****@greater thanone.com
Nov 22 '05 #8

On Fri, Feb 06, 2004 at 12:08:16PM -0500, Tom Lane wrote:
"Andy Kriger" <ak*****@greate rthanone.com> writes:
I would like to select strings from a table and return them as an array


You can do that beginning in 7.4 with the ARRAY(sub-select) construct.

regression=# select f1 from text_tbl;
f1
-------------------
doh!
hi de ho neighbor
(2 rows)

regression=# select array(select f1 from text_tbl);
?column?
----------------------------
{doh!,"hi de ho neighbor"}
(1 row)

regression=#

In prior versions you could probably fake it with a loop in a plpgsql
function, but it'd be kinda awkward.

regards, tom lane

---------------------------(end of broadcast)---------------------------
TIP 8: explain analyze is your friend


Joe Conway supplied a 7.3 version of function that
could help you do this. I have not tested it in
7.2, however. The details of this function for
getting the next array index for appending to the
array are written up in http://www.varlena.com/GeneralBits/24.html

CREATE OR REPLACE FUNCTION array_next(text[]) returns int AS '
DECLARE
arr alias for $1;
high int;
BEGIN
high := 1 +
replace(split_p art(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(myar ray)] = 'new element';
regression=# select * from mytable;
myarray
-----------------------------
{abc,"d e f","new element"}
(1 row)

Elein

---------------------------(end of broadcast)---------------------------
TIP 7: don't forget to increase your free space map settings

Nov 22 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
6452
by: point | last post by:
Hello there... I'm a PHP programmer and starting to learn JS... I have a following problem.... I have 3 select boxes! one is hotel one is destination and one is country... if someone clicks selects the country then the destination select box shows the destinations in that country and further if he chooses destination all
3
15630
by: Stewart | last post by:
Dear comp.lang.javascript, I have more than once wanted to manipulate the contents of select boxes dynamically, whilst the boxes contain <optgroup> tags. Manipulation of a select box containing only <option> tags is fairly easy and there is plenty of material on the net to assist with this. However, I have searched long and found the material on the subject of <optgroup> to be sparse, with a few posts here & there, but basically you're...
1
1401
by: supline | last post by:
I have a function that creates a select list: function make_select_ns($name,$array,$persist){ $string = "<select name=\"$name\">"; $string .="<option selected>" . ucfirst($name) . "</option>\n"; if ($name == $array){array_shift($array);} //removes duplicate when table name equals 1st item in array foreach ($array AS $value) { if (($value == $persist) && is_string($persist)){$selected = "selected";}
2
5247
by: BrianP | last post by:
Hi, I have had to invent a work-around to get past what looks like a JavaScript bug, the malfunctioning Perl-like JavaScript array functions including SPLICE() and UNSHIFT(). I have boiled it down to a very simple test case which can be cut-n-pasted into a .html file and viewed in a browser: ============================================================================
4
2481
by: Matt Ratliff | last post by:
Hello, I would appreciate any assistance you have with the following problem: I have (as an example) an array of values as follows: arrayvalues=new Array("0001","0003","0005") where each is the value of an option in a select statement: <select id="usertypes" multiple="multiple"> <option value="0033">data1</option>
1
4035
by: Sunray | last post by:
I have a form called the sales form and i have 2 sets of listboxes So what happens is. i add items form the bottom set of list boxes which are bound to a data base to the top set of list boxes which are not bound, I select from the bottom set and add to the top set which works fine, but now i decide to remove an item from the top set. when i tried to use a remove item code it worked fine, it did delete the item form the list but it added...
6
2417
by: cathyisfrustrated | last post by:
Hey, I've been trying to learn javascript for a few days. I'm a bit stuck! I'd appreciate any links to get me going in the right direction or any advice I can get. I've written a multidimensional array like this: var from_array = new Array(); from_array = new Array ( "Alice Springs", "1.5", "2.8"); new Array ( "Amberley", "1.5", "2.8") ;
25
5419
by: bonneylake | last post by:
Hey Everyone, Well i am not sure if my question needs to be here or in coldfusion. If i have my question is in the wrong section i am sorry in advance an will move it to the correct section. Basically i have a multiple select box. An it works except for this one part i want to add to it.The first box i have is called project members which shows the users you can choose to send an email to and the other box is called assignees which is the...
4
10693
tjc0ol
by: tjc0ol | last post by:
Hi guys, I'm a newbie in php and I got error in my index.php which is: 1054 - Unknown column 'p.products_id' in 'on clause' select p.products_image, pd.products_name, p.products_id, p.manufacturers_id, p.products_price, p.products_tax_class_id, IF(s.status, s.specials_new_products_price, NULL) as specials_new_products_price, IF(s.status, s.specials_new_products_price, p.products_price) as final_price from products_description pd,...
0
9751
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11027
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10682
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9513
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7917
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5942
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4563
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4159
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3187
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.