Re: SELECT INTO Array?

From: Michael Fuhr <mike(at)fuhr(dot)org>
To: Zitan Broth <zitan(at)mediasculpt(dot)net>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: SELECT INTO Array?
Date: 2005-04-01 06:19:36
Message-ID: 20050401061936.GA53355@winnie.fuhr.org
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Fri, Apr 01, 2005 at 03:22:58PM +1200, Zitan Broth wrote:
>
> I was wondering if there was an easy way of converting the output
> from a SELECT statement into an Array ..... I'd like to be able to
> SELECT INTO MyArray[] * FROM TABLE WHERE ID=1 ..... is this possible?

In 7.4 and later you can use an array constructor with a subquery
that selects a single column:

CREATE TABLE foo (
id integer PRIMARY KEY,
name text NOT NULL
);

INSERT INTO foo (id, name) VALUES (1, 'John');
INSERT INTO foo (id, name) VALUES (2, 'David');
INSERT INTO foo (id, name) VALUES (3, 'James');

SELECT ARRAY(SELECT id FROM foo WHERE name LIKE 'J%');
?column?
----------
{1,3}
(1 row)

Here's a PL/pgSQL example:

DECLARE
a integer[] := ARRAY(SELECT id FROM foo WHERE name LIKE 'J%');

Selecting multiple columns into an array doesn't work in SQL or
PL/pgSQL -- that could cause problems in the general case because
columns might have different types and arrays contain elements of
the same type. However, some other languages' interfaces to
PostgreSQL can return rows as arrays (e.g., Perl DBI).

--
Michael Fuhr
http://www.fuhr.org/~mfuhr/

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Nageshwar Rao 2005-04-01 06:28:57 Re: not able to connect to Database
Previous Message Glen Eustace 2005-04-01 05:07:50 Re: Inconsistent values for 'now'