How do you explode or unnest an array (or JSON array) into rows for analysis, and when is this technique needed?
Last updated
Unnesting turns one row holding an array into one row per element (parent columns repeated), so you can filter, join, or
GROUP BYindividual elements such as tags, line items, or JSON arrays.Syntax varies: Postgres
UNNEST/jsonb_array_elements, BigQueryCROSS JOIN UNNEST, SnowflakeLATERAL FLATTEN, SparkLATERAL VIEW explode.Use
WITH ORDINALITYto keep element position, andLEFT JOIN LATERALto keep parent rows whose arrays are empty or NULL.
- https://medium.com/@harsh1995hg/the-power-of-unnest-and-pivot-simplifying-complex-data-structures-in-sql-fa6ad2f53acf
- https://dev.to/sandonjacobs/array-expansion-in-flink-sql-40c9
- https://medium.com/@yudayreddy1/understanding-snowflakes-flatten-function-a-beginner-friendly-guide-to-working-with-csv-json-84ebfdbdfcc6