Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Column definitions in ROWS FROM() with multiple unnest calls

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'?

like image 667
hooblei Avatar asked Jan 10 '16 18:01

hooblei


People also ask

What does Unnest function do?

UNNEST takes an ARRAY and returns a table with a single row for each element in the ARRAY . Because UNNEST destroys the order of the ARRAY elements, you may wish to restore order to the table.

How do I Unnest two arrays in BigQuery?

Can We Unnest Multiple Arrays? When we use the UNNEST function on a column in BigQuery, all the rows under that column is flattened all at once. Currently, the UNNEST function does not accept multiple arrays as parameters. We need to merge the arrays into a single array before flattening it.

What is the use of Unnest in PostgreSQL?

The purpose of unnest function in PostgreSQL is to expand the array into rows. Unnest function generates a table structure of an array in PostgreSQL. Unnest array function is beneficial in PostgreSQL for expanding the array into the set of values or converting the array into the structure of the rows.


1 Answers

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
like image 61
Kristján Avatar answered Sep 30 '22 09:09

Kristján