Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create (explode) separate rows using two array columns in presto/SQL

if we have two arrays with same shape. How do we create/explode the separate rows for each element in array associated with other element in second array in Presto SQL.

For eg.,

|           Array1         |           Array2          |
| ------------------------ | ------------------------- |
| [0, 1, 34, 55, 68, 100]  | [40, 10, 30, 50, 60, 88]  |

Desired result

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel


| Column_a | Column_b |
| -------- | -------- |
|     0    |    40    |
|     1    |    10    |
|    34    |    30    |
|    55    |    50    |
|    68    |    60    |
|   100    |    88    |

I tried using

SELECT Column_a, Column_b FROM a
CROSS JOIN UNNEST(Array1) AS t (Column_a)
CROSS JOIN UNNEST(Array2) AS t (Column_b) 

But it gives output with every other array element.

>Solution :

UNNEST allows flattening several arrays at a time:

SELECT Column_a, Column_b 
FROM a
CROSS JOIN UNNEST(Array1, Array2) AS t (Column_a, Column_b)

If length of the arrays differ then the shorter one will be padded with null‘s

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading