Chapter 11 · Lesson 1 of 4
Unnesting Lists into Rows
Turn each element of a DuckDB list column into its own row with UNNEST, such as giving every product tag a separate row.
UNNEST turns each element of a list column into its own row. This is essential when working with JSON or other data that stores arrays inside columns.
If the products table has a tags column of type VARCHAR[], you can expand it:
SELECT name, unnest(tags) AS tag
FROM productsFor a product with two tags, this produces two rows — one per tag. The other columns are repeated for each expanded element.
An empty list produces zero rows for that input, so the parent row disappears from the result. NULL lists also produce zero rows. The sample data includes both cases so you can see that they do not appear after unnesting.
DuckDB supports the convenient SELECT unnest(...) form. Other databases often use a lateral join or CROSS JOIN UNNEST syntax instead.
Sample data
This lesson loads the products table (5 rows with tag lists) into DuckDB in your browser with one click, so you can run every example without uploading anything.
Setup SQL for products
CREATE OR REPLACE TABLE products (
name VARCHAR,
tags VARCHAR[]
);
INSERT INTO products VALUES
('Widget', ['electronics', 'sale']),
('Gadget', ['electronics', 'premium']),
('Gizmo', ['accessories', 'sale', 'new']),
('Doodad', []::VARCHAR[]),
('Mystery', NULL);Practice challenge
Unnest the tags column so each tag gets its own row. Return name and tag, ordered by name, then tag.
Hint: SELECT name, unnest(tags) AS tag FROM products ORDER BY name, tag
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.