Chapter 11 · Lesson 3 of 4
Recursive UNNEST for Nested Data
Flatten nested lists in one step with UNNEST and recursive := true, turning a list of lists into individual values in DuckDB SQL.
When lists contain other lists, a single UNNEST only peels off one layer. Use the recursive parameter to flatten all levels at once.
SELECT unnest([[1, 2], [3, 4, 5]], recursive := true)Without recursive this returns two rows — each inner list as a value.
With recursive := true it returns five rows — the individual integers.
This works on structs too. A list of structs with recursive unnesting first expands the list into rows, then expands each struct into columns:
SELECT unnest([{'a': 1, 'b': 2}, {'a': 3, 'b': 4}], recursive := true)Note that lists inside structs are not unnested — recursive unnesting first fully unnests all lists, then fully unnests all structs.
Sample data
This lesson loads the matrices table (2 rows with nested integer lists) into DuckDB in your browser with one click, so you can run every example without uploading anything.
Setup SQL for matrices
CREATE OR REPLACE TABLE matrices (
label VARCHAR,
grid INTEGER[][]
);
INSERT INTO matrices VALUES
('A', [[1, 2], [3, 4]]),
('B', [[5, 6, 7], [8]]);Practice challenge
Recursively unnest the grid column to get individual integers. Return label and the unnested value as val, ordered by label, val.
Hint: SELECT label, unnest(grid, recursive := true) AS val FROM matrices ORDER BY label, val
Run your query in the editor and the lesson checks the result automatically.
Lessons in UNNEST
Flatten DuckDB lists and structs into rows and columns with UNNEST, including recursive flattening and max_depth.
Related guides
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.
How to Flatten Nested JSON with SQL: Structs, Lists, and UNNEST
Nested JSON becomes STRUCT and LIST columns in DuckDB. Learn how to reach into structs, turn arrays into rows, and aggregate the flattened result.