liveBook · Manning

Unnest

As explained in DuckDB in Action

unnest is a DuckDB SQL function that expands nested list or struct values into rows or columns.

unnest expands nested list values into individual rows, making JSON arrays easier to inspect, normalize, and query. By default it unpacks one level; recursive := true handles deeper nesting. section 5.3

Shred home and away shot arrays

FROM 'xg/shots_*.json' SELECT unnest(h) AS row UNION ALL FROM 'xg/shots_*.json' SELECT unnest(a) AS row LIMIT 3;

Each unnested value remains a STRUCT. Cast the whole STRUCT when inconsistent inferred types need correction, then expose its fields with row.* and query the result through a view.

Query the flattened result

After creating shotsFlattened with SELECT row.*, aggregate xG and goals by team, filter season = 2022, and order by totalXG.

How DuckDB in Action covers it

How deep it goes
Demonstrates one-level expansion, recursive unpacking, STRUCT casting, field projection, views, and downstream aggregation.
Examples
Uses football shot JSON Lines, home and away arrays, inferred schemas, flattened views, and team-level expected-goals totals.
What it assumes
Assumes familiarity with SQL queries and JSON-derived nested arrays; demonstrates schema inspection before transformation.
What you can do after
Apply unnest in DuckDB SQL to turn nested JSON arrays into rows and query their STRUCT fields.
How it connects
Connects unnest with JSON, arrays, STRUCT values, UNION ALL, views, casting, and relational aggregation.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of DuckDB in Action. The section links point to the parts of the book it draws on.