Data models and query languages
Relational, document and graph models, and how the shape you pick makes some queries easy and others painful.
Updated since you finished it. We changed this lesson after you marked it done. Your progress is kept.
What broke
This story is made up, but it is a common one.
A small team builds an events app on MongoDB. Each event is one document. Inside it is an array of attendees: user id, name and photo URL. The event page loads with one read. It is fast and the code is simple.
Six months later, three requests arrive in the same sprint.
First, a user changes her name. Her old name still shows on 40 past events. Someone has to write a script that finds and updates every copy.
Second, a big conference sells 30,000 tickets. Its document keeps growing. Every read of the event page now loads all 30,000 attendees.
Third, product wants a page: "events your friends are going to". Users and events now link both ways, and the app has no easy way to ask that question. The team writes code that loads friends, then events, then filters in memory.
Nothing was wrong with MongoDB. The data had changed shape. It started as a tree, one event with its attendees. It became a web of users, events and friendships. The model had not changed with it.
The idea in simple words
A data model is the shape you give your data: tables, documents or a graph. A query language is how you ask the data questions.
Each model makes some questions cheap and others expensive. 2
- The relational model stores rows in tables. Tables point to each other with ids. You combine them with a join when you read.
- The document model stores a whole record, with its nested parts, as one JSON-like document. MongoDB is a common example. 7
- The graph model stores nodes and the links between them. Neo4j is a common example, and Cypher is its query language. 12
The key idea. Look at the relationships in your data. If records mostly contain their parts, a document fits. If many records point to many others, tables or a graph fit better. The model decides which queries are easy.
To pick a product, read Choosing a database. This lesson is about the shape of the data, which comes first.
How it works
Step through the diagram. It shows one rename in two models. Use Next and Back, or the ← and → keys.
- A stores a copy of each attendee's name inside every event. One read shows the whole event page. Asha has tickets for 3 events, so her name is stored 3 times.
- Asha changes her name. A must find and update all 3 copies. If one write fails, the events now disagree about her name.
- B keeps users and events in their own tables. A tickets table holds pairs of ids. This is how a relational model stores a many-to-many link. Some rows are not shown.
- In B the rename touches one row. The price moves to reads: to show an event page, B must join users, tickets and events.
Normalise or embed
Normalisation means each fact is stored in one place. Other rows point to it by id. A rename is one write. The cost moves to reads: you join tables to show a page.
Embedding puts related data inside the parent document. MongoDB's guide says to embed when one thing "contains" another and when you read them together. 8 It says to use references when the child list can grow without limit, or when the child can exist on its own. 8
Copying data to avoid joins is called denormalisation. MongoDB says duplicates can speed up reads. It also warns that if a copied field is updated often, a reference may be the better choice. 8
Many-to-many links
One user goes to many events. One event has many users. This is a many-to-many relationship.
In SQL you store it as a third table. The PostgreSQL docs show order_items, which links products and orders. It has two foreign keys, one to each table. 4 A foreign key means a value must match a row in the other table. The database rejects a ticket for a user that does not exist. 4 You can also choose what happens on delete. CASCADE removes the linked rows too. 4
In MongoDB you store ids and join with $lookup, a left outer join. 9 Its docs warn that it can be slow on large collections without an index on the joined field. 9
Schema-on-write and schema-on-read
In Postgres, a table has a fixed schema. The database checks every write against it. This is schema-on-write.
A MongoDB collection does not require all documents to have the same fields. 7 The structure still exists, but your reading code decides what it means. This is schema-on-read. 2 You can add a field without a migration. But your code must handle old documents that lack it. 10
The line is not sharp. MongoDB has schema validation: rules for field types and ranges. By default, it rejects writes that break them. 11 Postgres has jsonb columns for flexible parts. Its docs still advise a "somewhat fixed structure" for JSON documents. 5
Declarative and imperative queries
An imperative query is a loop you write: fetch users, then for each one fetch events. You choose the order and the method.
A declarative query says what result you want. SQL and Cypher both work this way. 12 2 The database's planner compares possible plans and join orders, and picks the cheapest. 3 When the data changes, it can pick a new plan with no change to your code. 2
Usually the new plan is better, but not always. A planner can suddenly switch to a slower plan as the data shifts. 2 So watch the plans of your most important queries.
Graphs and many hops
Cypher draws the pattern you want. (a:User)-[:FRIEND]->(b:User) reads like a picture of two nodes and an arrow. 12 A quantified relationship like -[:FRIEND]->{1,3} matches paths of one to three hops. 13
SQL can do this too, with WITH RECURSIVE. The query repeats a step until it finds no new rows. 6 The PostgreSQL docs warn that it can loop forever if the links contain a cycle. They show how to track the path, or use the CYCLE clause, to stop it. 6 So deep, variable hops are possible in SQL, but they are easier to write in a graph language.
Trade-offs
The cells sum up the sources. Some cells are this lesson's own advice, so test them on your own data.
| Option | Rename or update shared data | Read one record with its parts | Many-to-many and many hops | Schema |
|---|---|---|---|---|
| Relational, normalised | Yes One write. | No Needs joins. | Yes Join tables; WITH RECURSIVE for hops. 6 | On write, checked by the database. |
| Document, embedded | No Every copy must change. 8 | Yes One read, one atomic write. 8 | No $lookup or code; slow without an index. 9 | On read by default; validation is optional. 11 |
| Document, with references | Yes One write. | No Needs $lookup or several reads. | Partly. You search by ids in a way that is close to relational. 2 | Same as above. |
| Graph | Yes One node. | Partly. Fine for small shapes. | Yes Hops are part of the language. 13 | Usually flexible. |
Postgres with a jsonb column | Yes , for the table parts. | Yes , for the JSON parts. | Yes , for the table parts. | Mixed. Keep JSON documents small. 5 |
Simple rule: embed what is read together and owned by one parent. 7 Put anything shared by many parents in its own table or collection.
At work: how a senior uses this
- Start from the access patterns you listed in Choosing a database. For each one, ask: "Which data is read together?"
- For each relationship, write "one-to-one", "one-to-many" or "many-to-many". Many-to-many is the warning sign for heavy embedding.
- Ask: "Can this list grow without a limit?" If yes, do not embed it. MongoDB says the same. 8
- When you copy data for speed, write down who updates each copy, and how you find copies that disagree.
- Use a
jsonbcolumn for truly varied fields, like product attributes per category. Keep ids, money and status as real columns. - Add schema validation to a document collection once its shape settles. 11
- Add a graph database only when hop queries are a core feature. Try
WITH RECURSIVEfirst. - Read the query plan. A declarative query is fast only if the planner finds a good plan, which usually needs the right index. 3
With AI
What to ask the agent
"Here are our entities and the screens that read them. Draw a relational schema and a MongoDB document schema for them. For each query, say how many reads or joins it needs in each design."
"List every place this MongoDB schema copies the same data. For each copy, show the code that must change when the source changes."
"Rewrite this loop that fetches users, then their orders, as one SQL query. Then run EXPLAIN and tell me which indexes it uses."
What to check yourself
- The agent marked each relationship correctly. Many-to-many is easy to miss.
- Embedded arrays have a clear upper limit, such as "at most 50 addresses".
- Foreign key columns you join or delete on have an index. Postgres does not create it for you. 4
- The agent did not put money, ids or status inside a JSON blob without a reason.
- A recursive query has a stop rule, so a cycle cannot loop forever. 6
- Each copied field has a named owner and an update path.
Check yourself
Your progress is saved only in this browser. Export it to keep it safe.
You have finished 5 lessons. Your progress lives only in this browser. Export a copy so you don’t lose it.
Go deeper
Show 13 sources and related lessons
- Martin Kleppmann, Designing Data-Intensive Applications, O'Reilly, 2017 (1st edition)
Chapter 2, “Data Models and Query Languages” The classic book-length comparison of relational, document and graph models, for further reading. - Martin Kleppmann, Databases (University of Cambridge lecture notes, 2026/27) (opens in a new tab)
Kleppmann's own notes on relational, document and graph models, schema-on-read and query optimisers. - PostgreSQL documentation, section 51.5: Planner/Optimizer (opens in a new tab)
How the planner compares possible plans and join orders and picks the cheapest. - PostgreSQL documentation, section 5.5: Constraints (Foreign Keys) (opens in a new tab)
Foreign keys, referential integrity, the products and orders many-to-many example, and ON DELETE rules. - PostgreSQL documentation, section 8.14: JSON Types (opens in a new tab)
json versus jsonb, containment queries, GIN indexes, and advice on document size and structure. - PostgreSQL documentation, section 7.8: WITH Queries (Common Table Expressions) (opens in a new tab)
WITH RECURSIVE, how it runs step by step, and how to stop it looping on cycles in a graph. - MongoDB Manual: Data Modeling (opens in a new tab)
Flexible schema, and the rule that data accessed together should be stored together. - MongoDB Manual: Embedded Data Versus References (opens in a new tab)
When to embed and when to reference, the cost of duplicated data, and single-document atomic writes. - MongoDB Manual: $lookup (aggregation stage) (opens in a new tab)
The left outer join stage, and why it needs an index on the joined field. - MongoDB Manual: Schema Versioning Pattern (opens in a new tab)
Old and new document shapes in one collection, and queries that must handle both. - MongoDB Manual: Schema Validation (opens in a new tab)
Rules for field types and ranges on a flexible-schema collection, and what happens to invalid writes. - Neo4j Cypher Manual: Overview (opens in a new tab)
Cypher as a declarative graph query language, and its ASCII-art pattern syntax. - Neo4j Cypher Manual: Variable-length patterns (opens in a new tab)
Quantified relationships such as -[:NEXT]->{1,3} for paths of one to three hops.
Related: Choosing a database · Data modelling for NoSQL · Product catalog modelling (coming soon) · Schema migrations without downtime · Transactions and isolation levels
- Choosing a database: pick a product from your access patterns, once you know your data's shape.
- Data modelling for NoSQL: design tables around queries in DynamoDB- and Cassandra-style stores.
- Product catalog modelling: attributes that differ by category, a common use for
jsonb. - Schema migrations: how to change a schema-on-write table without downtime.
- For a longer comparison of the three models, read chapter 2 of Designing Data-Intensive Applications (1st edition). 1