UNNEST: one row per array element
You need it when a column holds a list (the tags of an order, the items of a cart, the words of a name) and you want to count, filter or join its elements.
SELECT o.order_id, t.tag
FROM order_tags o
CROSS JOIN UNNEST(o.tags) AS t(tag);
Each order comes out once per tag, its other columns repeated: a sum of the order's amount now counts it once per tag.
The trap. An order whose list is empty or NULL gives zero rows, so it disappears from the result without an error,
and every count per order built on it is wrong. Keep it with a left join that always matches:
LEFT JOIN UNNEST(o.tags) AS t(tag) ON TRUE gives that order one row, with a NULL tag.
On your warehouse. Postgres accepts both forms as written. BigQuery writes CROSS JOIN UNNEST(o.tags) AS tag and
LEFT JOIN UNNEST(o.tags) AS tag, with no ON. Snowflake uses LATERAL FLATTEN(input => o.tags, OUTER => TRUE) f and
reads f.value; Databricks LATERAL VIEW OUTER explode(o.tags) t AS tag, or explode_outer(tags) in the SELECT.
Without OUTER, each of them drops the empty lists, as does DuckDB's shortcut SELECT order_id, UNNEST(tags).
The trap
WITH order_tags(order_id, tags) AS (VALUES (2101, ARRAY['gift', 'first_order']), (2102, CAST(ARRAY[] AS VARCHAR[])), (2103, NULL), (2104, ARRAY['subscription'])) SELECT o.order_id, t.tag FROM order_tags o CROSS JOIN UNNEST(o.tags) AS t(tag) ORDER BY o.order_id, t.tag;
| order_id | tag |
|---|---|
| 2101 | first_order |
| 2101 | gift |
| 2104 | subscription |
The fix
WITH order_tags(order_id, tags) AS (VALUES (2101, ARRAY['gift', 'first_order']), (2102, CAST(ARRAY[] AS VARCHAR[])), (2103, NULL), (2104, ARRAY['subscription'])) SELECT o.order_id, t.tag FROM order_tags o LEFT JOIN UNNEST(o.tags) AS t(tag) ON TRUE ORDER BY o.order_id, t.tag;
| order_id | tag |
|---|---|
| 2101 | first_order |
| 2101 | gift |
| 2102 | NULL |
| 2103 | NULL |
| 2104 | subscription |