UNNEST for Array Expansion

Concepts covered: Array Flattening

CROSS JOIN UNNEST(p.track_ids) AS t(track_id) pairs each playlist row with the elements of its own array, so a playlist holding 3 tracks becomes 3 rows that repeat its other columns. Adding WITH ORDINALITY appends a second output column that numbers the elements from 1, which keeps each element's position after it has left the array.

SELECT
  p.playlist_id,
  t.track_id,
  t.pos
FROM playlists AS p
CROSS JOIN UNNEST(p.track_ids) WITH ORDINALITY AS t(track_id, pos)
playlists
playlist_idtrack_ids
101t9,t4,t7
102t2,t5,t8
103

Playlists 101 and 102 each become 3 rows, numbered 1 to 3 in their original order. Playlist 103 holds an empty array, so it has nothing to pair with and is gone from the result, the way an INNER JOIN drops a row with no match. Three playlists go in and 6 rows come out.

Predicting the row count

The output row count is the sum of the array lengths, so cardinality predicts it before the query runs. Picture 2 million playlists, each holding 50 tracks. Unnesting track_ids gives a row per track. Unnesting track_ids and durations_sec in 2 separate CROSS JOINs pairs every track with every duration of its playlist, 2,500 rows per playlist, and all but 50 of them are wrong pairings.

FormOutput columnsRows per input row
`UNNEST(arr) AS t(x)``x``cardinality(arr)`
`UNNEST(arr) WITH ORDINALITY AS t(x, n)``x`, `n``cardinality(arr)`
`UNNEST(a, b) AS t(x, y)``x`, `y`The longer of the 2 lengths
`UNNEST(m) AS t(k, v)` on a map`k`, `v`Number of map entries
Any form on an empty or NULL arraynone0, so the row disappears

Several arrays in a single UNNEST

Listing 2 arrays inside a single UNNEST walks them in step: element 1 beside element 1, element 2 beside element 2. When one array is shorter, its missing slots come back as NULL, and the row count follows the longer array.

SELECT
  p.playlist_id,
  t.track_id,
  t.duration_sec
FROM playlists AS p
CROSS JOIN UNNEST(p.track_ids, p.durations_sec) AS t(track_id, duration_sec)
playlists
playlist_idtrack_idsdurations_sec
102["t2", "t5", "t8"][195, null, 260]
104["t1", "t3"][300]
Result
playlist_idtrack_idduration_sec
102t2195
102t5NULL
102t8260
104t1300
104t3NULL

Playlist 104 lists 2 track ids but only 1 duration, so t3 arrives with a NULL duration. Playlist 102's t5 also shows NULL, from a duration that was recorded as NULL. The 2 NULLs look identical in the output; when the difference matters, compare cardinality(track_ids) with cardinality(durations_sec) before unnesting.

Keeping rows whose array is empty

Dropping playlist 103 is correct when the question is about tracks and wrong when it is about playlists. A report of every playlist with its tracks must still list the empty and NULL ones. The fix hands UNNEST a single-element array holding NULL whenever the real array has nothing in it:

SELECT
  p.playlist_id,
  t.track_id
FROM playlists AS p
CROSS JOIN UNNEST(CASE WHEN cardinality(p.track_ids) > 0 THEN p.track_ids ELSE ARRAY[CAST(NULL AS VARCHAR)] END) AS t(track_id)
playlists
playlist_idtrack_ids
101["t9", "t4", "t7"]
103[]
105NULL
Result
playlist_idtrack_id
101t9
101t4
101t7
103NULL
105NULL

Playlist 101 still produces its 3 rows. Playlists 103 and 105 each produce a row with a NULL track_id. For playlist 105, cardinality(NULL) is NULL, the WHEN condition is not TRUE, and the ELSE branch supplies the placeholder. The CAST gives that NULL the VARCHAR type the real arrays have, so both branches return the same type.

Rebuilding arrays after UNNEST

Rows produced by UNNEST fold back into an array per group with ARRAY_AGG. Order is the trap: the database promises no order for the rows of a group, so write ARRAY_AGG(t.track_id ORDER BY t.pos) with the ordinality column to get the original sequence back. The last section of this lesson weighs when that round trip is worth its cost.

How many rows does this query return?

WITH carts (cart_id, skus) AS (
  VALUES
    (1, ARRAY['a', 'b', 'c']),
    (2, CAST(ARRAY[] AS ARRAY(VARCHAR))),
    (3, ARRAY['d', 'e']),
    (4, CAST(NULL AS ARRAY(VARCHAR)))
)
SELECT
  c.cart_id,
  s.sku,
  s.n
FROM carts AS c
CROSS JOIN UNNEST(c.skus) WITH ORDINALITY AS s(sku, n)

About this lesson

This section is part of the Complex Data: Advanced lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.