9

I would like to use multiple arrays within a select clause. The obvious one didn't work and postgresql points to ROWS FROM() ...

select * from unnest(array[1,2], array[3,4]) as (a int, b int);

ERROR:

UNNEST() with multiple arguments cannot have a column definition list  
LINE 1: select * from unnest(array[1,2], array[3,4]) as (a int, b in...
                                                         ^
HINT:  Use separate UNNEST() calls inside ROWS FROM(), and attach a column definition list to each one.

...

select * from rows from (unnest(array[1,2]), unnest(array[3,4])) as (a int, b int);

ERROR:

ROWS FROM() with multiple functions cannot have a column definition list  
LINE 1: ...from (unnest(array[1,2]), unnest(array[3,4])) as (a int, b i...
                                                             ^
HINT:  Put a separate column definition list for each function inside ROWS FROM().

The manual explains this as well but how to define these 'separate column definitions'?

hooblei
  • 3,210
  • 2
  • 20
  • 17

1 Answers1

17

You can define the column names without their types using just AS t(a, b):

#= SELECT * FROM unnest(array[1,2], array[3,4,5]) AS t(a, b);
 a | b
---+---
 1 | 3
 2 | 4
 ∅ | 5

To define types, do it on the arrays themselves:

#= SELECT a / 2 AS half_a, b / 2 AS half_b
   FROM unnest(array[1,2]::float[], array[3,4,5]::integer[]) AS t(a, b);
 half_a | half_b
--------+--------
    0.5 |      1
      1 |      2
      ∅ |      2
Kristján
  • 18,165
  • 5
  • 50
  • 62
  • Ah thank you. I tried various variants and just missed every time the name/prefix (`t` in your example) before the column definition. – hooblei Jan 10 '16 at 19:00