Predictive Hacks

How to Flatten an Array in PostgreSQL

Assume that we are dealing with the following table called tbl

| name  | values  |
+-------+---------+
| hello | {1,2,3} |
| world | {4,5,6} |
| world |         |

and we can to flatten it as follows:

| name  | value |
+-------+-------+
| hello | 1     |
| hello | 2     |
| hello | 3     |
| world | 4     |
| world | 5     |
| world | 6     |
| world |       |

Notice the null value that we value for the values in the last row.

We can flatter it using the unnest function and the left join operation so that to include the NULL values.

SELECT t.name, v.value
FROM   tbl t
LEFT   JOIN unnest(t.values) v(value) ON true;

References

[1] Stack Overflow

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore

Python

Image Captioning with HuggingFace

Image captioning with AI is a fascinating application of artificial intelligence (AI) that involves generating textual descriptions for images automatically.

Python

Intro to Chatbots with HuggingFace

In this tutorial, we will show you how to use the Transformers library from HuggingFace to build chatbot pipelines. Let’s