Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store select query's output in one array in postgres

My code is:

SELECT column_name FROM information.SCHEMA.columns WHERE table_name = 'aean' 

It returns column names of table aean.
Now I have declared an array:

DECLARE colnames text[] 

How can I store select's output in colnames array.
Is there any need to initialize colnames?

like image 294
mitesh Avatar asked Jun 19 '11 11:06

mitesh


People also ask

How do I select an array in PostgreSQL?

PostgreSQL allows us to define a table column as an array type. The array must be of a valid data type such as integer, character, or user-defined types. To insert values into an array column, we use the ARRAY constructor.

How do you assign a selected value to a variable in PostgreSQL?

In PostgreSQL, the select into statement to select data from the database and assign it to a variable. Syntax: select select_list into variable_name from table_expression; In this syntax, one can place the variable after the into keyword.

Can we store array in PostgreSQL?

PostgreSQL allows columns of a table to be defined as variable-length multidimensional arrays. Arrays of any built-in or user-defined base type, enum type, composite type, range type, or domain can be created.


1 Answers

There are two ways. One is to aggregate:

SELECT array_agg(column_name::TEXT) FROM information.schema.columns WHERE table_name = 'aean' 

The other is to use an array constructor:

SELECT ARRAY(     SELECT column_name      FROM information_schema.columns      WHERE table_name = 'aean' ) 

I'm presuming this is for plpgsql. In that case you can assign it like this:

colnames := ARRAY(     SELECT column_name     FROM information_schema.columns     WHERE table_name='aean' ); 
like image 123
Denis de Bernardy Avatar answered Sep 19 '22 17:09

Denis de Bernardy