Nested Data
The nested design holds the same facts in one table. The shipping_address column holds an object, and the items column holds a list of objects.
Why 1NF said no, and what changed
First Normal Form told you to keep every column atomic, and a comma-separated string like 'SKU-1,SKU-7' is the classic violation. The database sees one opaque string, so it cannot type-check or count the pieces without parsing the string, and filtering on one piece needs the same parsing. Nested types keep the structure visible. A nested column declares its inner structure in the schema, so the engine knows that items is a list and that each element holds sku and quantity plus unit_price, each with a declared type. You relax 1NF on purpose, and the engine still enforces types on every inner value.
| Type | Holds | Relationship it embeds | Example |
|---|---|---|---|
| STRUCT | A fixed group of named, typed fields | 1:1 | shipping_address |
| ARRAY | An ordered list of same-typed elements | 1:N | items |
| MAP | Key-value pairs whose keys vary by row | 1:N, looked up by key | product attributes |
The 4-question test
- Owned?Does the child exist only because of this parent?An order item means nothing without its order. A product exists whether or not anyone orders it.
- Read together?Do queries that read the parent nearly always want the child?An order page shows its items every time. It rarely shows the customer's full profile.
- Bounded?Is there a known, small ceiling on how many children one parent has?An order holds tens of items. A customer can hold thousands of orders over the years.
- Frozen?Do the children stop changing once the parent is written?Items are fixed at checkout. A product's price and description keep changing.
One no is enough to normalize. A product fails the first question: it is shared by many orders, so embedding the full product in every order would copy its name and description into each one, the update anomaly from the normalization lessons. The order keeps a sku that points to the product table, and the product keeps its own row.
- Parent and children arrive in one read, with no join
- The grain stays one row per order, so COUNT(*) counts orders
- A child cannot be orphaned, because it lives inside its parent
- Questions about children across parents need the list expanded first
- Changing one child rewrites the whole parent row
- No key or foreign key constraint applies to values inside the row
A help desk app stores one row per support ticket. 2 new requirements arrive, and each one asks where the new data should live.
| ticket_idBIGINTPK | customer_idBIGINTFK | subjectVARCHAR | opened_atTIMESTAMP |
|---|
Agents tag each ticket with up to 5 labels such as 'billing'. Labels show every time a ticket opens and are never edited one by one. Where do they go?
Here is the orders table with its 2 address columns. The SQL in this lesson writes a struct type as ROW(...), listing each field name with its type.
Reading fields with a dot
NULL struct or NULL field
| order_id | billing_address | billing_address.postal_code | billing_address IS NULL |
|---|---|---|---|
| 1001 | {Torstr. 12, Berlin, 10119, DE} | '10119' | false |
| 1002 | NULL | NULL | true |
| 1003 | {Rue Oberkampf 5, Paris, NULL, FR} | NULL | false |
Orders 1002 and 1003 both return NULL for billing_address.postal_code, and only the IS NULL test on the struct tells them apart. With flat columns such as billing_street and billing_city, a missing address has to be inferred from all 4 fields being NULL at once.
Struct, flat columns, or its own table
A struct sits between 2 designs you already know. Against flat prefixed columns, it wins on naming and reuse: one shape serves shipping and billing, and related fields stay grouped under one name. Against a separate addresses table, it wins when the object has no identity of its own. An embedded address is a copy taken at checkout. If the customer moves next month, order 1001 still shows the Berlin address it shipped to, which is the correct record of that order.
What the fixed shape gives and takes
- ▸A misspelled field such as
shipping_address.ctiyfails when the query is checked, before any row is read. - ▸Each field keeps its own type:
postal_codestays a VARCHAR and alatfield can be a DOUBLE. - ▸Adding a field changes the schema once. Rows written earlier return NULL for it.
- ▸Structs nest:
shipping_address.geo.latreaches a struct inside a struct. - ▸Every row carries the same fields. Attributes that differ by row need a MAP, and repeated values need an ARRAY.
A payments table needs to store each charge's amount together with its currency, for instance 49.90 and 'EUR'. Every charge has exactly one such pair, and the pair is never shared between charges. Which model fits?
| order_id | shipping_fee | tags | items |
|---|---|---|---|
| 1001 | 5.00 | ['gift', 'express'] | [{SKU-1, 2, 10.00}, {SKU-7, 1, 30.00}] |
| 1002 | 5.00 | ['gift'] | [{SKU-7, 3, 30.00}] |
| 1003 | 0.00 | [] | [] |
Order 1003 is an abandoned order with empty lists. An empty array and a NULL array are different values: [] says the list is known and has no elements, and NULL says the list is unknown.
Working on the list in place
| order_id | line_count | first_sku | is_gift |
|---|---|---|---|
| 1001 | 2 | SKU-1 | true |
| 1002 | 1 | SKU-7 | true |
Positions start at 1, and asking for a position past the end of the list is an error, which is why the filter removes the empty order 1003 first. Sequence is part of the data: items[1] is the first line the customer added, and it stays first on every read.
UNNEST: one row per element
Other questions are about the elements across all orders, such as revenue per SKU. For those, UNNEST expands the array: a row with N elements becomes N rows, each carrying one element next to a copy of the parent's columns. With an array of structs, each field becomes its own column.
| order_id | shipping_fee | sku | quantity | unit_price |
|---|---|---|---|---|
| 1001 | 5.00 | SKU-1 | 2 | 10.00 |
| 1001 | 5.00 | SKU-7 | 1 | 30.00 |
| 1002 | 5.00 | SKU-7 | 3 | 30.00 |
3 orders went in and 3 rows came out, and the match is a coincidence. The grain is now one row per order line: order 1001 fills 2 rows, and order 1003 is gone because its list had nothing to expand. To keep parents with empty lists, write LEFT JOIN UNNEST(o.items) AS t (sku, quantity, unit_price) ON TRUE, which returns order 1003 once with NULL item columns.
Fan-out double counts parent columns
After the expansion, every parent column is repeated once per element. SUM(shipping_fee) over the expanded rows returns 15.00, because order 1001's fee of 5.00 is counted on each of its 2 lines. The true total across the 3 orders is 10.00. Sum element columns after unnesting, and sum parent columns before it.
SKU-7 from appearing twice in one order's items, and no foreign key checks that SKU-7 exists in the product table. If your model needs either guarantee, the pipeline that writes the array has to enforce it.- Embed lists with a known ceiling, such as the lines of one order
- Filter parent rows before unnesting, so fewer rows are expanded
- Embed a list that grows without limit, such as every order a customer places
- Rely on an array for elements that are updated one at a time
The playlists table has 3 rows. Playlist 1 has track_ids [10, 20, 30] and 100 followers, playlist 2 has [20] and 40 followers, and playlist 3 has [] and 7 followers. What does this query return?
| product_id | name | category | attributes |
|---|---|---|---|
| 501 | Laptop 14 | laptop | {brand: 'Acme', ram_gb: '16', screen_in: '14'} |
| 502 | Crew tee | shirt | {brand: 'Loom', size: 'M', color: 'navy'} |
| 503 | Camp mug | mug | {brand: 'Kiln', capacity_ml: '350'} |
A map is a child table folded into the row
The normalized version of this column is a table product_attributes with the composite key (product_id, attribute_name) and one value column. Product 501 would own 3 rows there. A map stores those same pairs inside the product row, and the composite key's rule carries over: within one map, each key appears once.
The other alternative is a wide table with one column per attribute. Its columns run ram_gb, screen_in, size, color, capacity_ml, and the list grows with every category. Each new category adds columns through a schema change, and each row leaves most of them NULL.
Looking up a key
2 forms read a value by key, and they differ on a missing key. The subscript attributes['ram_gb'] raises an error on any row whose map lacks that key, which here is every shirt and mug. The function element_at(attributes, 'ram_gb') returns NULL for those rows, so it is the form to use when keys vary.
The CAST is the price of one value type. Every value in this map is a VARCHAR, so '16' is text until the query converts it. Compared as text, '8' >= '16' is true, because the character 8 sorts after the character 1. A laptop with '8' would pass a text filter meant for 16 and above.
Keys nobody checks
A struct field is declared in the schema, so a typo fails loudly. A map key is a string in the data, so element_at(attributes, 'ram_gbs') runs without complaint and returns NULL for every row. Writers drift too: if one team writes ram_gb and another writes RAM, the map accepts both. Audit the keys by expanding map_keys, which returns each row's keys as an array.
| attribute_key | product_count |
|---|---|
| brand | 3 |
| ram_gb | 1 |
| screen_in | 1 |
| size | 1 |
| color | 1 |
| capacity_ml | 1 |
The audit shows brand on all 3 products. A key that appears on nearly every row and is filtered on often has stopped being a flexible attribute. Promote it to a real column with a real type, and keep the map for the long tail of keys that differ by category.
- Field names live in the schema
- Each field has its own type
- A wrong name is an error
- A new field is a schema change
- Keys live in the data
- All values share one type
- A wrong key returns NULL
- A new key needs no schema change
A fleet of delivery vehicles reports readings. Vans send fuel_pct and engine_temp. E-bikes send battery_pct and motor_temp. Cargo drones send battery_pct too, plus altitude_m and rotor_rpm. New vehicle types join every quarter. Every report also carries vehicle_id and reported_at, which every query filters on. Which column design fits?
Most analytic engines store tables by column. A row layout writes order 1001's values next to each other, then order 1002's. A columnar layout writes every order_id together, then every ordered_at together, and so on. A query that touches 2 columns out of 50 reads those 2 and never opens the other 48.
Nested fields become leaf columns
A columnar file splits every nested column into its leaves, the innermost scalar fields, and stores each leaf as its own column. shipping_address becomes 4 leaf columns, and items becomes 3. Alongside each leaf of an array, the file keeps small counters that record where one row's list ends and the next begins, so the engine can rebuild each row's list.
Take an orders table holding 200 million orders and keep only order_id and ordered_at along with shipping_address and items. The file sees 9 leaf columns.
| Leaf column | Comes from | Size on disk |
|---|---|---|
| order_id | top level | 0.8 GB |
| ordered_at | top level | 0.8 GB |
| shipping_address.street | STRUCT | 3.0 GB |
| shipping_address.city | STRUCT | 0.6 GB |
| shipping_address.postal_code | STRUCT | 0.5 GB |
| shipping_address.country | STRUCT | 0.1 GB |
| items.sku | ARRAY of STRUCT | 2.4 GB |
| items.quantity | ARRAY of STRUCT | 0.4 GB |
| items.unit_price | ARRAY of STRUCT | 1.2 GB |
The engine reads only the leaves a query names. Counting orders per country names shipping_address.country and nothing else. Revenue per SKU names the 3 items leaves. SELECT * names all 9. Add up the sizes each query needs.
This is called column pruning, and it is why a struct adds almost no read cost in an engine that prunes nested fields: shipping_address.country is about as cheap to scan as a top-level country column would be.
Why a map key cannot be pruned
A map has 2 leaves: one column holding every key of every row, and one holding every value. The products table stores attributes as 1.3 GB of keys and 1.8 GB of values. A filter on element_at(attributes, 'brand') has to read all 3.1 GB, because the brand values are interleaved with RAM sizes and every other attribute value in the same values column. Once brand is promoted to its own top-level column of 0.05 GB, the same filter reads 62x less.
Skipping data with min and max
Columnar files also keep the minimum and maximum of each leaf for every chunk of rows. A filter such as ordered_at >= DATE '2026-11-01' lets the engine skip every chunk whose maximum falls before that date. The statistics work best for a top-level column or a struct field, where each row contributes one value. They are blunt for array elements, where a chunk's range covers every element of every list, and of little use for map values, where '16' shares one range with 'M' and 'navy'.
- ▸Keep the date and id columns that most queries filter on at the top level or in a struct field.
- ▸Select the leaf fields you need.
SELECT *and whole-struct selects read every leaf. - ▸Promote a map key to a typed column once most rows carry it and queries filter on it.
- ▸Filter on parent columns before UNNEST, so chunks are skipped before any list is expanded.
The listings table has these leaf sizes: listing_id 0.5 GB, host.country 0.1 GB, host.name 1.0 GB, photos.url 6.0 GB, and the amenities map at 2.0 GB of keys plus 1.0 GB of values. The query below reads 3.1 GB. Which change removes the most from that read?
> A food delivery marketplace rebuilds its orders table for analytics. Each order has one drop-off address, between 1 and 30 dishes, and restaurant-specific options such as spice level or bun type that differ by cuisine. Analysts ask for revenue per dish, orders per city, and how often 'extra spicy' is chosen.
restaurant_id.dropoff_address holds one object per order, copied at checkout. dropoff_address.city answers orders per city.dishes is an array of structs. Revenue per dish needs UNNEST, and the delivery fee is summed before the expansion so it is counted once per order.options map, because a burger's option keys differ from a curry's. The team audits the keys and promotes spice_level once most dishes carry it.spice_level became its own column.element_at, so audit the keys and promote the common ones.Model objects, lists and flexible attributes inside a row, and know what each choice costs to query.
- Category
- Data Modeling
- Difficulty
- intermediate
- Duration
- 15 minutes
- Challenges
- 12 hands-on challenges
Topics covered: The Nesting Decision, STRUCT: Embedded Objects, ARRAY: Ordered Collections, MAP: Dynamic Key-Value Pairs, Columnar Storage & Nesting
Lesson Sections
- The Nesting Decision
An online store records order 1001: 2 line items, shipped to one address in Berlin. The normalized design you already know splits that order across 3 tables and reassembles it with joins. A nested design keeps the whole order in one row and stores the address and the items inside its columns. Why 1NF said no, and what changed 3 nested types cover the relationships you already model with tables. The 4-question test Nesting moves a child table inside its parent row. That is a good trade only when
- STRUCT: Embedded Objects
A STRUCT is one column value that holds a fixed set of named fields, each with its own type. Every row has exactly one struct in that column, or NULL, which makes it the embedded form of a 1:1 relationship. The order's shipping address is the standard case: 4 fields that always travel together and belong to this order alone. Reading fields with a dot A dot reaches into the struct, and the result is an ordinary typed value that works anywhere a flat column would, from the SELECT list to a join co
- ARRAY: Ordered Collections
An ARRAY column stores an ordered list in each row, with every element of the same type. The list in a row can be empty or hold any number of elements, so an array is how a 1:N relationship lives inside the parent row. Elements can be scalars, as in a list of tags, or structs, as in an order's line items. Working on the list in place Some questions are about the list as a whole, and array functions answer them without changing the grain. The result still has one row per order. UNNEST: one row pe
- MAP: Dynamic Key-Value Pairs
In a product catalog, a laptop has RAM and a screen size while a shirt has a size and a color. A mug has only a capacity. No fixed list of fields describes all 3, and next month the store adds bicycles. A MAP column handles this: each row stores its own set of key-value pairs, and the keys are data, free to differ from one row to the next. A map is a child table folded into the row Looking up a key Keys nobody checks A map buys flexibility and pays for it at read time. How large that payment is
- Columnar Storage & Nesting
Nested fields become leaf columns Why a map key cannot be pruned Skipping data with min and max Deciding what belongs inside the row is a modeling choice. What each query pays to read it is a storage choice, set by how the file splits nested columns into leaves.