Relational vs Document Data Models
How tables with joins and self-contained documents each fit the shape of your data, and how to choose between them for a service.
Overview
A data model is the shape you give your data when you store it. The two shapes most services choose between are tables (the relational model, used by PostgreSQL and MySQL) and documents (JSON-like trees, used by MongoDB and similar stores). Neither is better in general. Each one makes some reads and writes easy and others awkward, and the right choice depends on how the pieces of your data connect.
Why the choice exists: objects are trees, tables are flat
Application code usually holds data as nested objects: a user with a list of addresses, each with its own fields. A relational database stores the same data as flat rows in several tables, linked by keys. Something has to translate between the two, and that translation is called the impedance mismatch. Object-relational mappers (ORMs) such as Hibernate or Django's ORM do the translation for you, but they cannot hide it completely: you still think about joins, lazy loading and how many queries a page makes.
Key concepts
- Impedance mismatch
- Normalization
- Denormalization
- Locality
- Foreign key
- Many-to-many relationship
- jsonb
- $lookup
Interview questions
- When would you choose a document database over PostgreSQL?
- What is the impedance mismatch, and how do teams deal with it?
- A user profile has jobs, and each job has a company. Would you embed or reference the company?
- Has the difference between relational and document databases disappeared?
Sign up free to read the full topic
More DDIA topics
- Modes of Dataflow: Databases, Services, Messages
- Multi-Leader Replication
- OLTP vs OLAP
- Ordering and Causality
- Partitioning Strategies: Range vs Hash
- Rebalancing Partitions
- Reliability, Scalability, and Maintainability
- Replication Lag and Consistency Anomalies
- Schema Evolution and Backward/Forward Compatibility
- Schema-on-Read vs Schema-on-Write
- Secondary Indexes and Index Trade-offs
- Secondary Indexes on Partitioned Data
Start free on Cariara · Coding problems · System design studio