Chapter 11 · Lesson 2 of 4

Unnesting Structs into Columns

Expand a STRUCT column into separate columns with UNNEST, such as splitting an address struct into city and zip columns.

When a column holds a STRUCT, UNNEST expands its fields into separate columns.

If the contacts table has an address column of type STRUCT(city VARCHAR, zip VARCHAR):

SELECT name, unnest(address)
FROM contacts

This produces columns name, city, and zip — one column per struct field.

Note the difference from list unnesting: lists expand vertically (more rows), while structs expand horizontally (more columns). The row count stays the same.

This is especially useful when importing JSON data where objects are stored as DuckDB structs.

Sample data

This lesson loads the contacts table (3 rows with address structs) into DuckDB in your browser with one click, so you can run every example without uploading anything.

Setup SQL for contacts
CREATE OR REPLACE TABLE contacts (
    name VARCHAR,
    address STRUCT(city VARCHAR, zip VARCHAR)
  );

INSERT INTO contacts VALUES
    ('Alice', {'city': 'Boston', 'zip': '02101'}),
    ('Bob', {'city': 'Denver', 'zip': '80201'}),
    ('Carol', {'city': 'Boston', 'zip': '02102'});

Practice challenge

Unnest the address struct so city and zip become their own columns. Return name, city, and zip, ordered by name.

Hint: SELECT name, unnest(address) FROM contacts ORDER BY name

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