Learn SQL Lesson

Controlling Depth with max_depth

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_list

With `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.

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.

Open interactive editor