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