1

I need something similar to unnest(), but for unnesting to columns rather than rows.

I have a table which has id column and array column. How can I unnest array to columns? Arrays with same ids always have same array length.

EDIT: I'm seeking for query which would work with any array lenght

SELECT ???? FROM table WHERE id=1;

id | array                array1 | array2 | ... | arrayn
---+----------            -------+--------+-----+-------
 1 | {1, 2, ..., 3}    ->   1    |   2    | ... |   3
 1 | {4, 5, ..., 6}         4    |   5    | ... |   6
 2 | {7, 8, ..., 9}

Anyone got idea?

5
  • What should happen for id 2? Commented Mar 21, 2019 at 11:01
  • select ar[1], ar[2] from (select string_to_array('a b c', ' ') ar) as sq; Commented Mar 21, 2019 at 11:01
  • Possible duplicate of PostgreSQL convert array returned from function to columns Commented Mar 21, 2019 at 11:05
  • Sorry, didn't mention that I want query to work with any array length Commented Mar 21, 2019 at 11:10
  • 2
    That's not possible. The number of columns of a query must be known before the query is executed. Commented Mar 21, 2019 at 11:26

1 Answer 1

1

Wouldn't this be the logic?

select array[1] as array1, array[2] as array2
from t
where id = 1;

A SQL query returns a fixed set of columns. You cannot have a regular query that sometimes returns two columns and sometimes returns one or three. In fact, that is one reason to use arrays -- it gives you the flexibility to have variable numbers of values.

Sign up to request clarification or add additional context in comments.

3 Comments

It works, but I'm seeking for query which works with any array length
@Simonas have you found the solution?
@Sergei, no, I haven’t. Instead I first query for array_upper and generate final query on application side.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.