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.
See it run
One set of data in two models, a decision made row by row, and moving without stopping.
Operations
Same data, two models
Alice's book and pen, first as tables and then as one document, with two questions.
Step 1 of 4
Two tables
| order | user_id | product |
|---|---|---|
| 1 | 1 | Book |
| 2 | 1 | Pen |
users: 1 = Alice
The user is one row in users. The orders are two rows that hold the user's id.
Step 1: Two tables
tables: users(id, name), orders(id, user_id, product)document: { _id: 1, name: Alice, orders: [Book, Pen] }question 1: Alice with the ordersquestion 2: who bought a pen?- Strong at
- Tables: any question
- Costs
- Document: one read
Ask which question is frequent and which is merely possible.
In the real world
The same sql or nosql doing real jobs. Pick one and step through it.
Stores are added one at a time, each for a reason.
Step 1 of 4
One store
Everything is in PostgreSQL, pictures included.
Step 1: One store
Common mistakes
The bugs interviewers watch for, with the fix beside each.
One answer for the whole system
majorKinds of data differ in rules and rate.
Wrong"We are a NoSQL company."Rightorders: SQLsessions: key-valuefeed: wide-column, if the number asksScale without a number
criticalGiving up joins and constraints for 30 writes a second is a bad trade.
Wrong"It must scale, so no SQL."Right"30 orders/s at peak, 120 rows/s:one primary, trigger at the tested limit."Dual writes
criticalThe stores drift apart with no error.
Wrongdb.save(p)search.save(p)Rightdb.save(p)change stream -> searchEmbedding a list that never ends
majorEach read grows, and a document has a size limit.
Wronguser.orders = [ 40,000 orders ]Rightorders refer to the useruser.recent = [ last 5 ]
Interview tips
How to explain it
- Decide per kind of data.
- Questions, rules, numbers.
- Choice, reason, cost, trigger.
Memory trick
- SQL: Strict, Quality, Linked.
- NoSQL: Not only SQL.
- Case for what must be kept, bag for what changes.
Lean to SQL when
- Rules cross records.
- Questions are not known yet.
- One machine can hold it.
Lean to NoSQL when
- One known access by key, beyond one machine.
- Uneven records read whole.
- Short-lived data or long walks.