SQL Dojo
Keyword

UNNEST: one row per array element

UNNEST turns an array into rows, one per element, next to the columns of its row; written carelessly, it drops the rows whose array is empty.

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_idtag
2101first_order
2101gift
2104subscription
Try it in Randori

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_idtag
2101first_order
2101gift
2102NULL
2103NULL
2104subscription
Try it in Randori