All lessonsDay 16A-Foundations2026-10-14

Data Models and Query Languages: Tables, Documents, and How You Ask

You need to store a profile like Bill Gates on LinkedIn. One profile has one name, many past jobs, many schools, and links to companies and other people. The choice you make now decides if reads are one lookup or many joins.

1970Edgar Codd proposes the relational model. Data lives in tables of rows.
1968 to mid-1980sIBM IMS ships in 1968 with a tree model. By the mid-1980s relational systems become the default. That dominance lasts around 25 to 30 years.
2009The term NoSQL starts as a meetup hashtag for open source, distributed, nonrelational databases. It is later read as Not Only SQL.
user_id 251Example profile in this lesson: user_id 251. Two positions. Two schools. One region id us:91. One industry id 131.

Key points

  • Relational tables expose all rows for filtering. The optimizer picks the access method.
  • JSON documents group a tree together. That gives locality for whole object reads.
  • IDs remove duplication for regions and industries. Text copies invite inconsistency.
  • Declarative queries state the pattern. Imperative code states the steps.
  • History repeats. Document trees echo the hierarchical model. The join problem returns with many to many data.
01Derive when a one to many tree fits in one document and when it needs separate tables.
02Break down a resume read into queries and joins for both the relational schema and the JSON form.
03Argue schema on read versus schema on write for a rename from name to first_name and last_name.
04Predict what breaks when you add recommendations and company pages to a join free document store.
01

Problem: one profile, four pressures


You must store user 251 with first name, last name, summary, region, industry, photo, positions, education, and contact info.

Numbered requirements:

  1. (1)Fetch the whole profile fast enough to render a page.
  2. (2)Keep region names like Greater Seattle Area and industry names like Philanthropy spelled and linked consistently.
  3. (3)Grow to company pages, school pages, and recommendations where many users point to many shared entities.
  4. (4)Change shape over time, for example split name into first_name and last_name, without long downtime.

The tension is locality versus linkage. Requirement (1) wants everything in one place. Requirements (2) and (3) want shared references. Requirement (4) wants easy evolution.

Operable: tap requirements to feel the pull. (1) pulls toward locality. (2) and (3) pull toward linkage. (4) sits in the middle.

Locality: one placeLinkage: shared refs

Follow user 251 end to end. One profile, four pressures. The bar shows where the active requirements pull you.
02

Mental model: layers and shapes


Think in layers. Your objects sit on JSON or tables. That model sits on bytes on disk. Each layer hides the layer below.

Now think in shapes. A relation is an unordered set of rows. A document is a self contained tree. A tree fits a resume. A table fits a shared list.

Picture user 251 as a root with branches for positions and education. That is the document shape. Picture separate piles for users, positions, education, contact_info, regions, and industries linked by IDs. That is the relational shape.

Operable: switch shape. Same user 251, two physical pictures.

tree: 1 object
User 251 as a rooted tree versus six linked piles. Tree gives locality. Piles give linkage by ID.
03

Mechanism: shredding versus nesting


Relational: shred the tree

In the normalized relational form, you create users, positions, education, contact_info, regions, and industries. Each position row carries user_id 251. Region us:91 and industry 131 live once in their own tables.

Read path for one profile. Query users by user_id. Query positions by user_id. Query education by user_id. Query contact_info by user_id. Or do a messy multiway join. You then join region and industry IDs to get display names.

Write path for a rename. IDs never need to change. If Seattle changes its display name or you localize Philanthropy, you update one row. This breaks (2) if you instead copy plain text everywhere, because some copies update and others do not.

Document: nest the tree

In JSON you store one document for user 251. Positions is an array with two entries. Education is an array with two entries. Contact info is a nested object with blog and twitter. Region and industry remain IDs.

Read path for one profile. One query returns the whole tree. This serves (1) well. Storage is one continuous encoded string in JSON, XML, or BSON.

Write path for a nested item. You cannot point directly to the second position. You must say the second item in positions for user 251. Updates usually rewrite the whole document. Only size preserving edits are easy in place.

Failure case. Add recommendations. User 467 writes a recommendation for user 251. The recommendation must show the author name and photo. If the author changes the photo, all shown copies must change. If you denormalize the photo into each recommendation, that breaks (3) on update. If you store a reference to user 467, you now need a join or follow up queries. Early document stores had weak join support. RethinkDB supported joins. MongoDB did not at the time of writing. CouchDB only supported joins in predeclared views. So you emulate the join in application code with extra round trips. That is slower and more complex.

Operable: press Run to replay the resume read for user 251. Count queries and joins.

ready

Shredded tables

Q1 users WHERE user_id = 251Q2 positions WHERE user_id = 251Q3 education WHERE user_id = 251Q4 contact_info WHERE user_id = 251JOIN regions us:91 + industries 131

4 queries + 1 join step

Nested JSON

Q1 get document 251 (whole tree)

1 query, 0 joins

Same page render. Shredded needs many lookups plus ID joins for display names. Nested needs one lookup.

Operable: pick a photo strategy, then change the author photo and watch consistency versus query cost.

author 467
v1 photo
Rec on 251: photo v1 + text
Rec on 251 (2nd page): photo v1 + text

Recommendation from user 467 on user 251. Copies go stale. References need a join or follow up queries, which early MongoDB and CouchDB views handled poorly.
04

Weakness: we solved this before


The hierarchical model in IBM IMS stored nested trees like JSON. It was good for one to many data. It made many to many hard. It had no joins. Developers either duplicated data or resolved references by hand.

The network model or CODASYL generalized the tree. A record could have multiple parents. That models many to one and many to many. Links were like stored pointers. The only access was an access path from a root by following chains.

The problem with access paths was rigidity. Query code moved a cursor record by record. Programmers tracked many paths in their heads. If you lacked a path, you rewrote query code. Adding a new access pattern meant rewriting the application.

The relational model laid data open as tables. You select rows by condition. You insert without fixing pointers first. Foreign keys are resolved at query time, not at insert time. This breaks the old rigidity, but it moves work to the query optimizer. The optimizer picks order and indexes once for all apps.

Lesson for today. Document stores returned to hierarchical nesting for one to many data. For many to one and many to many they use document references, which are IDs like foreign keys. That part is not fundamentally different from relational. The debate returns when data gets interconnected.

Operable: drag the era slider. Watch the same resume idea change shape.

1970: relational
1970: relational tables

IMS trees to CODASYL pointers to Codd tables to JSON return. The join problem returns with many to many data.
05

Fix and its price: declarative queries and flexible schema


Declarative wins for new access patterns

An imperative query lists steps and order. A declarative query lists pattern and result shape. SQL follows relational algebra.

Show code: shark filter in SQL
SELECT * FROM animals WHERE family = 'Sharks';

The database can move records, add an index, or parallelize across cores. The query still works. Imperative list code may depend on order and must be rewritten to use a new index. The same gap appears in browsers. CSS declares li.selected > p and the browser updates styling automatically. The JavaScript loop over li elements needs manual updates and misses automatic cleanup.

Price of declarative. The language is less general. You trust the optimizer. Optimizers took years of research. But you build it once and all apps benefit.

Operable: add an index and a core. See which code survives untouched.

Declarative SQL
SELECT * FROM animals WHERE family = 'Sharks'

State: works before and after. Optimizer picks the new path.

Imperative loop
for each animal in order: if family match, collect

State: order dependent. Rewrite to use the index.

New access pattern without rewriting the app is the relational win.

Schema on write versus schema on read

Schema on write means the database enforces structure. Schema on read means code assumes structure when reading. Document stores and JSON in relational systems often use schema on read. The term schemaless is misleading because readers still assume fields.

Change example for requirement (4). Split name into first_name and last_name.

Document style fix in application code:

Show code: lazy fill at read time
if (user && user.name && !user.first_name) {
  // Documents written before Dec 8, 2013 do not have first_name
  user.first_name = user.name.split(" ")[0];
}

Relational style fix with migration:

Show code: ALTER plus UPDATE
ALTER TABLE users ADD COLUMN first_name text;
-- PostgreSQL variant (illustrative host, chapter grounded syntax):
UPDATE users SET first_name = split_part(name, ' ', 1);

ALTER TABLE is milliseconds in most systems. MySQL at the time of writing copied the whole table, so large alters could take minutes or hours. UPDATE rewrites every row and is slow on large tables. The workaround is the same as documents. Leave NULL and fill at read time.

Price list. Schema on read helps when data is heterogeneous or controlled by outside systems. Schema on write helps when all records should share shape, because it documents and enforces the contract. Schema changes have a slow reputation that is only partly deserved.

Operable: size the users table, then compare full UPDATE versus lazy fill at read time for the name split.

100k rows
Downtime
0 ms

blocking migration

Rows rewritten
0

UPDATE cost

Req (4) risk
low

long downtime risk

MySQL copy behavior at the time of writing versus millisecond ALTER elsewhere. Large UPDATE cost is why both models use lazy fill.

Locality and convergence

Documents win when you read most of the document together. They lose when you read a small slice of a large document, because the store loads the whole string. They lose on growing writes, because growth forces rewrite. Guidance from the field is keep documents small and avoid size increasing writes.

Locality is not unique to documents. Google Spanner can interleave child rows inside parent rows. Oracle has multi table index cluster tables. Cassandra and HBase use column families for similar locality. Relational systems added XML since the mid 2000s with indexing inside documents. PostgreSQL since version 9.3 and IBM DB2 since version 10.5 added JSON with query and index support. The models are converging toward a hybrid.

Operable: grow the document. The slice you need stays fixed, so waste grows.

20 units
needed slice (4)loaded waste

Whole string loads even for a small slice. Keep documents small and avoid growth that forces rewrite.
06

Code: three ways to ask the same question


Goal. Count shark sightings per month from an observations table or collection. Filter family equals Sharks. Group by month. Sum num_animals.

A. Declarative SQL

Show code: SQL monthly sharks
SELECT date_trunc('month', observation_timestamp) AS observation_month,
       sum(num_animals) AS total_animals
FROM observations
WHERE family = 'Sharks'
GROUP BY observation_month;

Notes on lines that matter. WHERE filters before grouping. date_trunc('month', ...) normalizes timestamps to month starts. GROUP BY plus sum aggregates. You do not name indexes or join order. The optimizer does.

B. MongoDB MapReduce with declarative filter

Show code: MapReduce monthly sharks
db.observations.mapReduce(
  function map() {
    var year = this.observationTimestamp.getFullYear();
    var month = this.observationTimestamp.getMonth() + 1;
    emit(year + "-" + month, this.numAnimals);
  },
  function reduce(key, values) {
    return Array.sum(values);
  },
  {
    query: { family: "Sharks" },
    out: "monthlySharkReport"
  }
);

Notes on lines that matter. query is declarative and MongoDB specific. map runs once per matching document and emits month string to count. Pairs group by key. reduce runs once per month key and sums. Output goes to monthlySharkReport. Functions must be pure. No extra queries. No side effects. That lets the system run and retry anywhere in any order.

Sample input to output. Two December 1995 shark documents with 3 and 4 animals emit ("1995-12", 3) and ("1995-12", 4). Reduce sees ("1995-12", [3, 4]) and returns 7.

Operable: play the worked trace for December 1995. Two docs in, one sum out.

2 docs: 3 + 4 animals
doc A: 1995-12, 3doc B: 1995-12, 4emit (1995-12, 3)emit (1995-12, 4)group [3, 4]reduce = 7 to monthlySharkReport

Press Play. Map must stay pure so the system can run and retry anywhere.

Filter is declarative. Map and reduce are user functions restricted to pure code for flexible placement.

C. Resume shapes

Relational shredding needs users plus positions plus education plus contact_info plus regions plus industries. JSON nesting for user 251 is one object with arrays:

Show code: user 251 JSON
{
  "user_id": 251,
  "first_name": "Bill",
  "last_name": "Gates",
  "region_id": "us:91",
  "industry_id": 131,
  "positions": [
    {"job_title": "Co-chair", "organization": "Bill & Melinda Gates Foundation"},
    {"job_title": "Co-founder, Chairman", "organization": "Microsoft"}
  ],
  "education": [
    {"school_name": "Harvard University", "start": 1973, "end": 1975},
    {"school_name": "Lakeside School, Seattle", "start": null, "end": null}
  ],
  "contact_info": {
    "blog": "http://thegatesnotes.com",
    "twitter": "http://twitter.com/BillGates"
  }
}

Use this to rehearse aloud. State the read path for each model. State where the join lives.

07

Field guide: who uses what and why


Operable: filter by design motive. Each card keeps its why.

MongoDB, CouchDB, RethinkDB, EspressoStore JSON trees.Why: closer to application objects and one lookup locality for whole documents.
PostgreSQL with JSON since 9.3, IBM DB2 since 10.5, Oracle, MS SQL ServerRelational tables plus XML or JSON with index and query inside documents.Why: keep joins plus borrow document locality.
MySQL in this chapterRelational, but ALTER TABLE copies the table.Why it matters: schema change planning differs from other relational systems.
Google Spanner with interleaved tables, Oracle cluster tables, Cassandra and HBase column familiesRelational or wide column with locality grouping.Why: get document like locality without giving up the base model.
IBM IMSHierarchical trees.Why mentioned: it shows the old limit. Good for one to many, painful for many to many.
CODASYL network systemsMulti parent links with access paths.Why mentioned: it shows the cost of hand coded navigation.
Filter to compare motives. Locality grouping appears in both camps.

Rule from the chapter. Document like trees fit when you load the whole tree at once. Analytics event logs may never need many to many joins. Highly connected data favors relational as acceptable and graph models as most natural.

08

Interview ears


Why would you store region as us:91 instead of Greater Seattle Area?

Consistency, one place update, localization, and search. Seattle implies Washington through the region table, not through the string. Plain text duplicates human meaning and breaks (2) on rename.

When does a document model create more application code?

When you add many to many links like recommendations. You either denormalize and add consistency code, or emulate joins with multiple queries. That moves database work into the app and is usually slower.

Why did relational beat hierarchical and network for new features?

No hand maintained access paths. Declare a new index and queries use it. The optimizer owns order and index choice. That serves fast feature change.

Schema on read versus schema on write?

Pick schema on read for heterogeneous or externally controlled shapes. Pick schema on write when all records must share shape and you want enforcement and documentation. Both can do lazy migration at read time.

Declarative versus MapReduce style?

Declarative hides order and enables optimizer and parallel gains. MapReduce mixes declarative filter with user map and reduce functions, but restricts them to pure functions for flexible placement and retry.

09

Judgment quiz


Q1Predict. You store company name as plain text in every position. The company rebrands. What breaks? Cite the requirement number. What single schema change fixes it?

Some copies update and others do not, so Greater Seattle Area style renames fail. One row update via ID fixes (2). Plain text duplicates human meaning.

Q2Compare. Profile page load needs positions plus education plus contact info. Show the query count for shredded tables versus one JSON document. When would the JSON win shrink?

Shredded queries users, positions, education, contact_info plus joins for us:91 and 131. Nested returns the whole tree at once for (1). Slice reads load the whole string, so locality win fades.

Q3Choose under tradeoff. You must add recommendations where photo updates must appear everywhere, and you must ship fast with no downtime for a name split. Pick document reference versus denormalized copy for photos, and pick read time fill versus full UPDATE for names. Defend each pick by naming what breaks (1), (3), or (4) if you choose the other path.

Copies break (3) on photo change, all shown copies must change. Full UPDATE breaks (4) with slow rewrite on large tables. References need extra queries but stay correct, and lazy fill ships with no downtime.

Sources: Designing Data-Intensive Applications Chapter 2 by Martin Kleppmann. IBM IMS (1968) and CODASYL history. Codd relational model (1970). NoSQL meetup (2009). PostgreSQL 9.3 JSON, IBM DB2 10.5 JSON, Spanner interleaving, Oracle cluster tables, Cassandra and HBase column families as cited in chapter.