Learn SQL
DuckDB SQL UNNEST Explained: Lists, Structs, Recursive Flattening, and max_depth
UNNEST is the bridge from nested data to queryable rows and columns, especially when working with JSON-like lists and structs.
On This Page
Nested data needs shaping before analysis
CSV data is usually flat. JSON and Parquet data often contain lists and structs. UNNEST helps turn that nested shape into rows and columns you can filter, join, and aggregate.
SQL for Files runs DuckDB in the browser, making it a useful place to practice UNNEST on local nested files without uploading them.
Lists become rows
When a column holds a list, UNNEST turns each list element into its own row. The other selected columns are repeated for each element.
SELECT name, unnest(tags) AS tag
FROM products
ORDER BY name, tag;Structs become columns
A struct is different from a list. Unnesting a struct expands its fields horizontally into separate columns while keeping the row count the same.
SELECT name, unnest(address)
FROM contacts
ORDER BY name;Recursive UNNEST and max_depth control nested layers
recursive := true flattens nested lists all the way down. max_depth lets you peel off only a limited number of layers when you want to preserve part of the nested structure.
SELECT label, unnest(grid, recursive := true) AS val
FROM matrices
ORDER BY label, val;Practice the UNNEST chapter
- Unnest list columns into one row per element.
- Unnest struct columns into separate fields.
- Use recursive unnesting for deeply nested lists.
- Use max_depth to control how much nesting is removed.
Continue in the editor
Open SQL for Files to add your own CSV, JSON, or Parquet files and try these examples locally in your browser.
Open editorRelated guides
How to Analyze JSON Files Locally with SQL
Load JSON or NDJSON into a local DuckDB table, then use SQL to inspect records, filter fields, and work with nested values.
What Is DuckDB WASM and Why Use It for Browser SQL?
DuckDB WASM brings an analytical SQL engine into the browser, enabling local file analysis without a server-side database.
DuckDB Array Lambda Functions: list_transform, list_filter, and list_reduce Explained
DuckDB list lambdas let you map, filter, and reduce arrays inside SQL, creating compact pipelines for nested list data.