unnest

Applies to: ✅ Data 360 SQL ✅ Tableau Hyper API

Expands the elements of one or more arrays into a set of rows.

Syntax 

1unnest(<array> [, ...])

Arguments 

Required 

  • <array>: The array to expand.

Optional 

  • ...: Additional arrays to expand in lock-step.

Returns 

Returns a set of rows, each containing one element from the array(s). If multiple arrays are provided, they are expanded in lock-step. If the arrays aren’t all the same length, the shorter ones are padded with NULL values.

Examples 

Unnest an Array 

1SELECT * FROM unnest(ARRAY['Mon','Tue','Wed','Thu','Fri']) AS days(day)

Results:

day
Mon
Tue
Wed
Thu
Fri

Unnest an Array while numbering the rows 

The WITH ORDINALITY clause instructs unnest to also number the generated rows. Thereby, we know which element occured at which position in the original array.

1SELECT * FROM unnest(ARRAY['Mon','Tue','Wed','Thu','Fri']) WITH ORDINALITY AS days(day, ordinality)

Results:

dayordinality
Mon1
Tue2
Wed3
Thu4
Fri5

Unnest Multiple Arrays 

You can also call unnest with multiple array parameters. In this case, the arrays are expanded in lock-step. If the arrays aren’t all the same length, the shorter ones are padded with NULL values.

1SELECT * FROM unnest(
2  ARRAY['Mon','Tue','Wed','Thu','Fri', 'Sat', 'Sun'],
3  ARRAY['ramp up','work','work','work','wrap up'],
4) AS days(name, task);

Results:

nametask
Monramp up
Tuework
Wedwork
Thuwork
Friwrap up
SatNULL
SunNULL

Related Documentation