Chapter 11 · Lesson 4 of 4
Controlling Depth with max_depth
Control how far UNNEST flattens nested lists with max_depth, expanding only the outer level and keeping the inner lists intact.
Sometimes you want to peel off only a few layers of nesting rather than flattening everything. The max_depth parameter controls how many levels UNNEST removes.
SELECT unnest([[[1, 2], [3]], [[4, 5]]], max_depth := 1) AS inner_listWith max_depth := 1 this returns two rows — each is still a list of lists:
[[1, 2], [3]]
[[4, 5]]
With max_depth := 2 it goes one level deeper, returning inner lists:
[1, 2]
[3]
[4, 5]
max_depth implies recursive unnesting, so you do not need to specify recursive := true separately.
This is useful when your data has a known structure and you want to stop at a specific level — for instance, unnesting groups but keeping the items within each group as a list.
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
Use UNNEST with max_depth := 1 on the grid column to expand only the outer list. Return label and the partially unnested value as row_list, ordered by label. The result should have inner lists as values.
Hint: SELECT label, unnest(grid, max_depth := 1) AS row_list FROM matrices ORDER BY label
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.