2. Fast and cheap tables: partitions, clusters and nested data
2.3 Nested data: a list inside a row
Highlights & notes
Select lesson text to highlight it, or tap Add note.
Bookmarks
Bookmark a lesson to see it here.
One order can have many items: a laptop and a mouse. The classic design keeps two tables, orders and order_items, and joins them. BigQuery offers another way: keep the items inside the order row.
Two building blocks:
- STRUCT: a small group of named fields, like
(product, price) - ARRAY: a list of values. An ARRAY of STRUCTs is a list of items.
JSON files from apps already look like this, so they load neatly. To turn the list back into rows, use UNNEST. It gives one row per item, and repeats the order's columns next to each item.
The tiffin box idea
- A flat table: every food item is packed in its own box, with a label saying whose lunch it is
- A nested table: one tiffin per child, with all the items inside
UNNESTopens the tiffin and lays the items out one by one
Read a field inside a STRUCT with a dot: customer.city. Read the items of an ARRAY with UNNEST(items). A dot does not work on an ARRAY.
Make a nested table
Run this once to create the table used in the walkthrough.
CREATE OR REPLACE TABLE sales.orders_nested AS
SELECT 201 AS order_id,
[STRUCT('Laptop' AS product, 55000 AS price), ('Mouse', 700)] AS items
UNION ALL
SELECT 202,
[STRUCT('Keyboard' AS product, 1500 AS price)];How it fits together
- Order 201
- items: Laptop, Mouse
- UNNEST → 2 rows
Open the list with UNNEST
Each order row holds a list called items.
SQL
SELECT o.order_id, item.product, item.priceFROM sales.orders_nested AS o, UNNEST(o.items) AS itemWHERE item.price > 1000;
Rows at this step
order_id | product | price ---------+----------+------ 201 | Laptop | 55000 202 | Keyboard | 1500
Try it yourself
1. Run the Make a nested table script above.
2. Run the walkthrough query.
3. Change the filter to item.product = 'Mouse'. Which order comes back?
Question 1 · Easy
Which type holds a list of values in one cell?
Question 2 · Medium
Order 201 has 2 items and order 202 has 1 item. How many rows does UNNEST(items) produce in total?
Question 3 · Hard
The column customer is a STRUCT with the fields name and city. How do you read the city?
Key takeaways
A STRUCT groups fields and an ARRAY holds a list, so one order row can carry all its items. UNNEST turns the list back into one row per item.
Save your progress
Start free and your progress, code and notes stay saved. Free for 1 month, no card needed.
Start free Log in