Part 2 of 10
Relational versus document models
Edgar Codd proposed the relational model in 1970: data sits in relations (SQL tables), each an unordered set of tuples (SQL rows). At first many doubted it could be fast. By the mid-1980s, relational databases and SQL were the default for regularly structured data, and they still lead in fields like business analytics.
NoSQL in the 2010s was not one technology but a loose bundle of ideas: new data models, flexible schemas, scaling, and open source licenses. NewSQL tried to scale like NoSQL while keeping tables and transactions. What lasted is the JSON document model, made popular by MongoDB and Couchbase. Most relational databases now support JSON too, and JSON is often seen as more flexible than a "rigid" relational schema.
Objects versus rows
App code uses objects; a relational database stores rows. Translating between them takes a clumsy layer of code, and this gap is the impedance mismatch.
An ORM (like ActiveRecord or Hibernate) writes much of this translation for you, but has critics:
- It is complex and cannot fully hide the differences, so you still think in both worlds.
- ORMs serve OLTP apps, but data engineers building analytics query the raw tables, so table design still matters.
- Many only support relational OLTP databases, with poor support for search engines, graph stores, or NoSQL.
- Generated schemas can be awkward for people using the tables directly, and slow; customizing them can cancel the gain.
- Slow queries are easy to write, like the N+1 problem.
N+1: you load 30 orders in one query, then the ORM runs one more query per order to fetch its customer. That is 31 queries where one join would do. The fix is to tell the ORM to load customers together with the orders.
ORMs still help:
- Some translation is needed anyway, and ORMs remove repetitive code for simple cases (complex queries can be hand-written).
- Some cache query results to cut database load.
- Some help with schema migrations and admin tasks.
Documents for one-to-many data
Single values (title, cook time) fit as columns. Lists (ingredients, steps, tags) are one-to-many relationships.
- Relational: separate tables, each row pointing back to the recipe by a foreign key.
- Document: one JSON document with the lists nested inside.
The document is closer to the objects in your code. Some say JSON shrinks the impedance mismatch, and some count its lack of a schema as a plus (JSON has its own problems as an encoding, covered in chapter 5). It also has locality: one fetch gets the whole recipe, while tables need several queries or a messy join. One-to-many data forms a tree, and JSON makes the tree visible.
This suits one-to-few: a recipe has maybe 15 ingredients. If the "many" can be huge, like millions of comments on a viral video, one document gets unwieldy, and separate rows work better.