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 products

For 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.

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