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.

Open this lesson in the SQL editor

Lessons in UNNEST

Flatten DuckDB lists and structs into rows and columns with UNNEST, including recursive flattening and max_depth.

  1. 01 · Unnesting Lists into Rows
  2. 02 · Unnesting Structs into Columns
  3. 03 · Recursive UNNEST for Nested Data
  4. 04 · Controlling Depth with max_depth

Related guides