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.

BigQuery Arrays & Structs

Part 17 of 19

Everything you need to work effectively with nested and repeated data in BigQuery — ARRAY, STRUCT, UNNEST, ARRAY_AGG, and related functions.

Up next

Why you should think twice before UNNESTing arrays or date intervals

A practical reminder that not all simple solutions scale

More from this blog

D

Datawise — SQL, BigQuery & Python for Data Engineers

207 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.