SQL or NoSQL
easy 24 minThe useful question is not which is better but which questions, rules and numbers this part of the system has.
Video lesson · Chapter 1 of 5
The same customer in two representations
Theory
Read or listen first. About 1 min.
What it is
This is a decision topic. SQL databases keep related facts in tables and answer questions you did not plan. NoSQL databases arrange data for questions you did plan, in several shapes.
The decision is made per kind of data, not once per company. A shop can keep orders in tables, sessions in a key-value store and pictures in object storage, and be simple all the same.
Why it exists
A database is hard to change later. The data outlives the code, every service learns its habits, and moving it while people use it is a project of its own.
Most arguments about it are too general. "NoSQL scales" and "SQL is safe" are both half true. The answer appears when you write down the questions, the rules that must never break, and the numbers.
A short history
1970
Codd's paper proposes the relational model, which separates what data means from how it is stored.
2006 to 2007
The Bigtable and Dynamo papers show very large stores without a full relational model.
2009
NoSQL becomes the common name after a meeting organised by Johan Oskarsson.
2011
Martin Fowler writes about polyglot persistence: different stores for different kinds of data.
2012
Google's Spanner paper describes a global database with transactions, and weakens the old border.
Words to know
- Access pattern
- One question with its key, order, size and rate.
- Invariant
- A rule that must always hold, such as stock not below zero.
- Embed
- Put related data inside the parent record.
- Reference
- Store the other record's key and look it up.
- Schema on write, on read
- Shape checked when stored, or interpreted when read.
- Polyglot persistence
- Using several kinds of store in one system.
- Source of truth
- The copy that wins when copies disagree.
- Dual write
- Writing two stores from the app with nothing tying them together.
How it works
Step through the idea, or press Play.
Questions. What is read and written, by which key, how often
Understand it
Start here
Packing for a trip
A traveller packs. A fitted case has a slot for each thing: tidy, quick to check, and awkward when something new must come. A soft bag takes anything, and finding things later is the price. Neither is the better luggage.
Choose by what you carry and how you look for it.
The idea
Same data, two models
Alice ordered a book and a pen. In tables, the user and the orders are separate facts joined by a key. In a document, the orders live inside the user.
Tables: users (1, Alice) and orders
| orders.id | user_id | product |
|---|---|---|
| 1 | 1 | Book |
| 2 | 1 | Pen |
{ "_id": 1, "name": "Alice", "orders": [ { "id": 1, "product": "Book" }, { "id": 2, "product": "Pen" } ]}Who answers which question easily?
| Question | Tables | This document |
|---|---|---|
| Alice with the orders | Join by key | One read |
| Who bought a pen? | Filter orders by product | An index inside the array, or a scan |
| Pens sold per month | Group and sum | An aggregation, or another system |
| Rename a product everywhere | One row in products | Every document that holds it |
| Add a gift note to some orders | A new nullable column | Just write the field |
SELECT u.name, o.productFROM users uJOIN orders o ON u.id = o.user_idWHERE u.id = 1;-- MongoDB, the same question:-- db.users.findOne({ _id: 1 }, { name: 1, orders: 1 });Comparison
Side by side, with care
| Aspect | SQL tends to | NoSQL tends to |
|---|---|---|
| Data model | Tables with rows and columns | Documents, pairs, graphs, wide columns |
| Schema | Declared, checked on write | Flexible, understood on read |
| Scaling writes | Up first, then shards | Out by partition key |
| Transactions | Full, over many tables | Often one key or record; some products offer more |
| Joins | Native | Limited or none; some have lookups |
| Query language | A standard with dialects | Own language or API per product |
| Integrity | Foreign keys, checks, unique | Mostly in the application |
| Age | Since the 1970s | Modern use of the name since 2009 |
| Best at | Unknown questions, strict rules | Known access, uneven data, high rates |
Where the border blurs
JSON inside SQL
PostgreSQL's
jsonbstores and indexes documents in a column.Transactions in NoSQL
MongoDB has multi-document ACID transactions. DynamoDB groups up to 100 actions.
SQL that scales out
Spanner and CockroachDB spread tables over machines and keep transactions.
Schemas in NoSQL
MongoDB can validate documents. Cassandra tables have declared columns.
Decide
When SQL fits
- 1
Complex questions
Joins over several tables, sums, and questions nobody has asked yet.
- 2
ACID over several records
Payments and stock: several changes must happen together.
- 3
Structured data
The shape is known and shared by many programs.
- 4
Reports
Dashboards and ad hoc analysis at moderate size. Large ones belong in OLAP.
- 5
Strong consistency
Banking and bookings, where old data causes harm. See ACID.
Decide
When a NoSQL shape fits
- 1
Very high rate by key
Hundreds of thousands of operations a second that share nothing but the key.
- 2
Shapes that differ
Each record has its own fields, or they change often and few programs read them.
- 3
High write throughput
Devices, logs and events. Stores built on an LSM tree take writes well.
- 4
Nested data read whole
A page, a profile, a form: one document.
- 5
Short-lived data
Sessions and caches in a key-value store.
A path through the decision
Examples
Six real cases
| Data | Choice | Reason |
|---|---|---|
| Shop orders | SQL | Payment and stock must agree |
| User sessions | Key-value, such as Redis | Lookup by id, with a lifetime |
| Social feed | Wide-column, such as Cassandra | Many writes, read by user and time |
| Financial reports | SQL, or an OLAP copy of it | Joins and exact sums |
| Product catalogue | Document, such as MongoDB | Attributes differ by product |
| Bookings | SQL | A unique rule prevents double booking |
Numbers
Let a number decide
A shop: one million orders a day
A feed: 100 million posts a day, 200 followers each
Measure what one machine of yours can take with your own rows and indexes. A load test is worth more than any number on a web page, including the ones here.
Together
Polyglot persistence
Using several stores, each for what it does best, is called polyglot persistence. This is how a large shop could look.
Seven stores in one shop
Who keeps what
| Service | Store | Is it the truth? |
|---|---|---|
| User accounts | PostgreSQL | Yes |
| Orders | PostgreSQL | Yes |
| Sessions | Redis | Yes, but losing it only logs people out |
| Product catalogue | MongoDB | Yes |
| Search | Elasticsearch | No, a copy of the catalogue |
| Event analytics | Cassandra | No, a copy; large sums fit OLAP better |
| Recommendations | Neo4j | No, rebuilt from orders |
| Media | S3 (object storage) | Yes |
What you gain
- Each question is fast
- Parts scale separately
- A failure can stay local
What it costs
- More systems to run, patch and back up
- Data that disagrees for a while
- More skills in the team
- Harder monitoring and debugging
Keep copies in step without dual writes
Moving
Migration in both directions
SQL to NoSQL
- Decide what to embed and what to reference
- Redesign queries that used joins
- Move integrity checks into the app
- Plan for copies that lag
NoSQL to SQL
- Normalise records into tables
- Define a strict schema, and clean old shapes
- Add foreign keys after the data is clean
- Shard later if the size asks for it
Moving while people use it
- 1
Model the questions
Write each access pattern against the new model before copying a byte.
- 2
Copy and follow
Take a snapshot at a known point, then apply changes from that point. Updates carry a version.
- 3
Compare
Read both for a share of requests and count differences. Counts and sums catch what samples miss.
- 4
Switch reads
In small steps, with a switch back.
- 5
Switch writes
Once. Feed the former store from the new one for a while, so that you can return.
- 6
Remove
After the agreed time, and after a restore test of the new store.
The migration, and its way back
Embed or reference?
Summary
The whole topic in one minute.
Start from questions, rules and numbers. Related facts, unknown questions and rules across records point to SQL. A single known access by key, uneven records, or a write rate beyond one machine point to a specific NoSQL shape.
Both sides borrowed from each other, so compare products and settings. Add a second store only when a number or a question forces it, keep one source of truth, and feed the others from its changes.
- Decide per kind of data: questions, rules, numbers.
- SQL keeps unknown questions and cross-record rules easy.
- A NoSQL shape pays off for one known access at scale or uneven data.
- Compare products and settings; the old border has blurred.
- Several stores need one source of truth and copies fed from its changes.
- Migrate by snapshot, change stream, comparison, then small switches.