ARRAY can only contain items of the same type.
Your example displays the value of text and integer (without quotes around 1 ). It is generally not possible to mix types in an array. To get these values ββinto an array, you must create a composite type and then form an array of this composite type, as you already mentioned.
Alternatively, you can use json data types in Postgres 9.2+, jsonb in Postgres 9.4+, or hstore for key-value pairs.
Of course, you can cast integer to text and work with a two-dimensional text array. Consider the two syntax options for entering an array in the demo below and refer to the guide for entering an array .
There is a limitation to overcome. If you try to aggregate ARRAY (to build from a key and a value) into a two-dimensional array, there is an error in assembling the array_agg() aggregate or the ARRAY constructor:
ERROR: could not find array type for data type text[]
There are ways around this.
Combining key-value pairs in a two-dimensional array
PostgreSQL 9.1 with standard_conforming_strings= on :
CREATE TEMP TABLE tbl( id int ,txt text ,txtarr text[] );
The txtarr column is for demonstration of syntax options in the INSERT command only. The third row contains metacharacters:
INSERT INTO tbl VALUES (1, 'foo', '{{1,foo1},{2,bar1},{3,baz1}}') ,(2, 'bar', ARRAY[['1','foo2'],['2','bar2'],['3','baz2']]) ,(3, '}b",a{r''', '{{1,foo3},{2,bar3},{3,baz3}}');
A simple case: aggregate two integers (I use them twice) into a two-dimensional int array:
Update: Better with custom aggregation function
Using the polymorphic type anyarray it works for all base types:
CREATE AGGREGATE array_agg_mult (anyarray) ( SFUNC = array_cat ,STYPE = anyarray ,INITCOND = '{}' );
Call:
SELECT array_agg_mult(ARRAY[ARRAY[id,id]]) AS x -- for int ,array_agg_mult(ARRAY[ARRAY[id::text,txt]]) AS y -- or text FROM tbl;
Note the optional ARRAY[] layer to make it multidimensional.
Update for Postgres 9.5 +
Postgres now sends the input option of the receiving array to array_agg() , and you can replace my custom function from above:
Leadership:
array_agg(expression)
...
input arrays combined into an array of one higher size (all inputs must have the same dimension and cannot be empty or NULL)