IntermediateData Modeling · 15 min · 12 challenges

Nested Data

In 2010, Google engineers published how they query web pages stored as nested records: one document holding its id, its lists of forward and backward links, and its names by language. A query counting forward links across a trillion-row table returns in seconds only if it can read that single nested field and skip the rest.

The Nesting Decision

Daily Life
Interviews
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.
orders
order_idPKBIGINT
customer_idFKBIGINT
ordered_atTIMESTAMP
shipping_address_idBIGINT
addresses
address_idPKBIGINT
streetVARCHAR
cityVARCHAR
postal_codeVARCHAR
countryVARCHAR
order_items
order_item_idPKBIGINT
order_idFKBIGINT
skuVARCHAR
quantityINTEGER
unit_priceDECIMAL(10,2)

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.

orders
order_idPKBIGINT
customer_idFKBIGINT
ordered_atTIMESTAMP
shipping_addressSTRUCT (4 fields)
itemsARRAY of STRUCT

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.

3 nested types cover the relationships you already model with tables.
TypeHoldsRelationship it embedsExample
STRUCTA fixed group of named, typed fields1:1shipping_address
ARRAYAn ordered list of same-typed elements1:Nitems
MAPKey-value pairs whose keys vary by row1:N, looked up by keyproduct attributes

The 4-question test

Nesting moves a child table inside its parent row. That is a good trade only when the child behaves like a part of the parent. Ask these 4 questions about the child data.
Embed when all 4 answers are yes
  • 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.

What embedding buys
  • 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
What embedding costs
  • 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
The help desk schemaStep 1
>

A help desk app stores one row per support ticket. 2 new requirements arrive, and each one asks where the new data should live.

tickets
ticket_idBIGINTPKcustomer_idBIGINTFKsubjectVARCHARopened_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?

The same 4 questions apply to every nested type in the sections that follow: owned, read together, bounded, frozen.

STRUCT: Embedded Objects

Daily Life
Interviews
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.

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.

CREATE TABLE orders (
order_id BIGINT,
customer_id BIGINT,
ordered_at TIMESTAMP,
shipping_address ROW(
street VARCHAR,
city VARCHAR,
postal_code VARCHAR,
country VARCHAR
),
billing_address ROW(
street VARCHAR,
city VARCHAR,
postal_code VARCHAR,
country VARCHAR
)
)

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 condition.
SELECT
shipping_address.country,
COUNT(*) AS order_count
FROM orders
WHERE shipping_address.city <> billing_address.city
GROUP BY shipping_address.country

NULL struct or NULL field

A struct gives you 2 distinct kinds of missing. Order 1002 was paid with a gift card and has no billing address at all, so the whole struct is NULL. Order 1003 has a billing address whose postal code was never collected, so the struct exists and one field inside it is NULL.
order_idbilling_addressbilling_address.postal_codebilling_address IS NULL
1001{Torstr. 12, Berlin, 10119, DE}'10119'false
1002NULLNULLtrue
1003{Rue Oberkampf 5, Paris, NULL, FR}NULLfalse

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.

The separate table is right when the object is shared or edited on its own. A customer's saved address book needs a key and its own rows, because one address there is reused across many orders and a correction has to land in one place.

What the fixed shape gives and takes

Consequences of a fixed set of fields
  • ▸A misspelled field such as shipping_address.ctiy fails when the query is checked, before any row is read.
  • ▸Each field keeps its own type: postal_code stays a VARCHAR and a lat field can be a DOUBLE.
  • ▸Adding a field changes the schema once. Rows written earlier return NULL for it.
  • ▸Structs nest: shipping_address.geo.lat reaches 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.
Multiple Choice

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?

A struct answers the 1:1 case. An order also has line items, and their number differs from order to order, which a fixed set of fields cannot hold.

ARRAY: Ordered Collections

Daily Life
Interviews
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.
CREATE TABLE orders (
order_id BIGINT,
shipping_fee DECIMAL(10, 2),
tags ARRAY(VARCHAR),
items ARRAY(
ROW(
sku VARCHAR,
quantity INTEGER,
unit_price DECIMAL(10, 2)
)
)
)
order_idshipping_feetagsitems
10015.00['gift', 'express'][{SKU-1, 2, 10.00}, {SKU-7, 1, 30.00}]
10025.00['gift'][{SKU-7, 3, 30.00}]
10030.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

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.
SELECT
order_id,
CARDINALITY(items) AS line_count,
items[1].sku AS first_sku,
CONTAINS(tags, 'gift') AS is_gift
FROM orders
WHERE CARDINALITY(items) > 0
order_idline_countfirst_skuis_gift
10012SKU-1true
10021SKU-7true

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.

SELECT
o.order_id,
o.shipping_fee,
t.sku,
t.quantity,
t.unit_price
FROM orders AS o
CROSS JOIN UNNEST(o.items) AS t(sku, quantity, unit_price)
order_idshipping_feeskuquantityunit_price
10015.00SKU-1210.00
10015.00SKU-7130.00
10025.00SKU-7330.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.

SELECT
t.sku,
SUM(t.quantity * t.unit_price) AS revenue
FROM orders AS o
CROSS JOIN UNNEST(o.items) AS t(sku, quantity, unit_price)
GROUP BY t.sku
TIP
An array has no key. Nothing stops 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.
✓Do
  • Embed lists with a known ceiling, such as the lines of one order
  • Filter parent rows before unnesting, so fewer rows are expanded
✗Don't
  • 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
Multiple Choice

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?

SELECT
COUNT(*) AS row_count,
SUM(p.follower_count) AS followers
FROM playlists AS p
CROSS JOIN UNNEST(p.track_ids) AS t(track_id)
Arrays hold elements you find by position or by scanning the whole list. When each value needs a name, and the names differ from row to row, the list becomes a set of key-value pairs.

MAP: Dynamic Key-Value Pairs

Daily Life
Interviews
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.
CREATE TABLE products (
product_id BIGINT,
name VARCHAR,
category VARCHAR,
attributes MAP(VARCHAR, VARCHAR)
)
product_idnamecategoryattributes
501Laptop 14laptop{brand: 'Acme', ram_gb: '16', screen_in: '14'}
502Crew teeshirt{brand: 'Loom', size: 'M', color: 'navy'}
503Camp mugmug{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.

SELECT
product_id,
name,
CAST(ELEMENT_AT(attributes, 'ram_gb') AS INTEGER) AS ram_gb
FROM products
WHERE CAST(ELEMENT_AT(attributes, 'ram_gb') AS INTEGER) >= 16

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.

SELECT
k AS attribute_key,
COUNT(*) AS product_count
FROM products
CROSS JOIN UNNEST(MAP_KEYS(attributes)) AS t(k)
GROUP BY k
ORDER BY product_count DESC
attribute_keyproduct_count
brand3
ram_gb1
screen_in1
size1
color1
capacity_ml1

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.

STRUCT
  • 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
MAP
  • Keys live in the data
  • All values share one type
  • A wrong key returns NULL
  • A new key needs no schema change
Multiple Choice

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?

A map buys flexibility and pays for it at read time. How large that payment is depends on how the engine stores nested columns on disk, which is the last piece of the model.

Columnar Storage & Nesting

Daily Life
Interviews

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 columnComes fromSize on disk
order_idtop level0.8 GB
ordered_attop level0.8 GB
shipping_address.streetSTRUCT3.0 GB
shipping_address.citySTRUCT0.6 GB
shipping_address.postal_codeSTRUCT0.5 GB
shipping_address.countrySTRUCT0.1 GB
items.skuARRAY of STRUCT2.4 GB
items.quantityARRAY of STRUCT0.4 GB
items.unit_priceARRAY of STRUCT1.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.

~1%
of the file read for orders by country
4.0 GB
read for revenue per SKU
9.8 GB
read by SELECT *

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

4 rules for nested columns
  • ▸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.
Multiple Choice

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?

SELECT
COUNT(*) AS pool_listings
FROM listings
WHERE host.country = 'JP'
AND ELEMENT_AT(amenities, 'pool') = 'true'
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.
PUTTING IT ALL TOGETHER

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

The nesting decision: dishes embed because the order owns them and reads them with it, and the list is capped at 30 and frozen at checkout. Restaurants are shared and edited, so the order keeps a restaurant_id.
STRUCT: dropoff_address holds one object per order, copied at checkout. dropoff_address.city answers orders per city.
ARRAY: 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.
MAP: each dish carries an 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.
Columnar storage: orders per city reads one leaf of the struct. The spice question read every option key and value until spice_level became its own column.
KEY TAKEAWAYS
Embed a child only if the parent owns it and reads it with it, and only if its size is bounded and it is frozen after writing. A single no sends it to its own table.
A STRUCT is a fixed set of typed fields, one per row. It can be NULL as a whole or hold NULL fields, and a misspelled field is an error.
An ARRAY holds zero to many same-typed elements in order. UNNEST changes the grain to one row per element and repeats every parent column.
A MAP holds keys that vary by row with one value type. A missing or misspelled key returns NULL from element_at, so audit the keys and promote the common ones.
Columnar files store each leaf field as its own column. Struct fields prune like top-level columns, while a map lookup reads every key and every value.

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

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

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

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

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

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