I’m trying to select for a two dimensional array of integers, and directing the output to a file. Is there any way that I can write a postgresql statement that would make the output of the select statement nicely formatted. As in each array of integers that is an element of the 2D array is on its own line.
Right now I just get this output:
SELECT array FROM table LIMIT 1;
{{0,0,0},{1,1,1},{2,2,2},{3,3,3},{0,0,0},{1,1,1},{2,2,2},{3,3,3}
,{0,0,0},{1,1,1},{2,2,2},{3,3,3},{0,0,0},{1,1,1},{2,2,2},{3,3,3}
,{0,0,0},{1,1,1},{2,2,2},{3,3,3},{0,0,0},{1,1,1},{2,2,2},{3,3,3}}
And I would like to get something more like this:
{0,0,0}
{1,1,1}
{2,2,2}
...
I can do this after the query returns with some parsing, but if its possible to do it in Postgres itself that would be ideal.
There are several ways. One way is to cast the array to text and split it up with regexp_split_to_table().
This function is present in PostgreSQL 8.3 or later.
Output:
If you want the enclosing brackets (maybe you don’t?), add them back like this:
Ourtput:
Alternative:
This should also work with PostgreSQL 8.2 or maybe even earlier, but I did not test that.
Output:
(You may want to strip some curly brackets ..)
Else, I would write a plpgsql function that loops through the array. Fairly easy.
There is also the related
unnest()function, but it returns a row per base element (integer in this case), so it’s no use here.One (fast!) way to output the result:
COPY.