Skip to main content

Command Palette

Search for a command to run...

How ARRAY() can function as UNPIVOT and UNNEST as PIVOT?

Updated
1 min read
How ARRAY() can function as UNPIVOT and UNNEST as PIVOT?
C

Senior Data Engineer • Contractor / Freelancer • GCP & AWS Certified

I’ve come across this SQL transformation multiple times, and it’s an interesting two-way problem.

1️⃣ From columns to rows (ARRAY as UNPIVOT):
We start with separate timestamps for different lifecycle events. To analyze events dynamically, we reshape them into an ARRAY<STRUCT>—essentially converting columns into rows, similar to UNPIVOT.

2️⃣ From rows back to columns (UNNEST as PIVOT):
If we have an array of events, we may need to do the opposite — bringing individual event types back into separate columns, similar to PIVOT. We achieve this by UNNESTing the array and using conditional aggregation (aggregation function + CASE WHEN).

Found it useful? Subscribe to my Analytics newsletter at notjustsql.com.

More from this blog

D

Datawise: A blog on SQL, BigQuery, Analytics, Python Tips and Tricks

204 posts

Data Engineer with a passion for transforming complex data landscapes into insightful stories. Here on my blog, I share insights, challenges, and the ever-evolving dance of technology and business.