SQL vs NoSQL and database types
What breaks
Section titled “What breaks”The salon platform from lesson 1.5 runs on one PostgreSQL database. Bookings, payments and the takings row sit in normalised tables, with indexes and transactions. It works.
Then it grows to a few thousand businesses, and one product meeting brings six requests.
- Sessions. Every page view looks up the visitor’s session by its id. A session dies after 30 minutes. Today it is a table, plus a nightly job that deletes dead rows.
- Business profiles. A salon lists hours and stylists, a tailor the measurements she takes. Each new kind of business is a migration.
- The message log. Every reminder is a row, written once, never changed, soon the largest table, and read only as “the last 50 messages for this customer”.
- Referrals. “Who did Ada refer, who did they refer, and so on down?” Each level is one more join.
- Metrics. Bookings per minute, per city, kept for a month and drawn as a line.
- Search. A customer types “something like knotless braids but shorter”. No row has those words.
Plain PostgreSQL can serve five of them, at a price. Sessions pay for a logged transaction on every page view. Profiles pay a migration per business type. Referrals pay a join per hop. Metrics pay to delete a month of rows one by one. And search cannot work at all: a B-tree finds values that are equal or in a range, not values that are near.
The relational database is built for flexible questions over related data. These six ask narrow questions of data with one shape. Each type of database in this lesson is one such shape made cheap.
Terms used in this lesson:
- An access pattern is one question the application asks of its data, with its rate: “fetch a session by id, a few hundred times a second”. A workload is all of them together.
- NoSQL is a loose name for databases that are not relational. It is a family, not one design.
- Schema on write means the database checks a record’s shape when it is stored, as PostgreSQL does. Schema on read means it stores what it is given, and the reading code makes sense of it.
Mental model
Section titled “Mental model”Every database is a set of questions made cheap, paid for by making other questions expensive. Relational makes almost any question possible at a moderate price. Each NoSQL type makes a few very cheap and the rest slow. So list the access patterns first, then pick the database whose cheap questions are the ones you ask most.
Diagram
Section titled “Diagram”The six requests as one decision. Each arrow is the main question; each box is what that type gives up.
So what does “SQL vs NoSQL” really ask?
Section titled “So what does “SQL vs NoSQL” really ask?”Whether you design for flexibility or for known questions. AWS puts the split plainly in its DynamoDB guide. In a relational database, “data can be queried flexibly, but queries are relatively expensive and don’t scale well in high-traffic situations”. In a NoSQL database, “data can be queried efficiently in a limited number of ways, outside of which queries can be expensive and slow.”
That reverses how you model. Lesson 1.4 normalised first and asked about queries later. Here, instead of reshaping data at query time with joins, the database “organizes data so that its shape in the database corresponds with what will be queried.”
Shaping data for each query means copying it into every shape that needs it: lesson 1.4’s denormalisation, done on purpose and everywhere. Every copy is one more write and one more place to drift.
Why accept that? Mostly for scale. A question that touches one key can be answered by whichever machine holds that key, so the data can spread across many machines. AWS says a relational database is “easiest to scale up with faster hardware”; spreading it across hosts “requires additional investment”. Splitting data is lesson 3.3; copies and how far they may disagree are 3.1 and 3.2.
Key-value: one key, one value
Section titled “Key-value: one key, one value”Take request 1. A session is read and written by its id and nothing else. Amazon’s 2007 Dynamo paper met the same pattern: “Most of these services only store and retrieve data by primary key and do not require the complex querying and management functionality offered by an RDBMS.” Its examples include shopping carts and session management; its answer is “a simple primary-key only interface”.
A key-value store is that interface: get, set and delete by key. Redis is one example, “an
in-memory data store” whose values can be strings, hashes or sorted sets. EXPIRE sets “a timeout
on key. After the timeout has expired, the key will automatically be deleted”, so the cleanup job
goes, and memory makes each lookup cheap.
What does memory cost? Durability, unless you configure it. With Redis snapshots “you should be prepared to lose the latest minutes of data”; with its append-only log and the default fsync every second, “you can only lose one second worth of writes”. Losing a second of sessions means a few people log in again. Losing payments is not acceptable, so the takings stay in PostgreSQL.
Gives up: every question that is not “this key”.
Document: the whole object, in one place
Section titled “Document: the whole object, in one place”Request 2. A tailor’s profile and a salon’s share a name and a phone number, and little else. In tables, each new business type is a migration, and the profile page joins five tables to draw one screen.
A document database stores each record as one nested, JSON-like document, and lets documents in a collection differ. MongoDB’s manual: “Documents within a single collection are not required to have the same set of fields or data types”, and new fields need no “schema migration”. Its core rule: “data that’s accessed together should be stored together.”
So the tailor’s document embeds her measurement list, and the salon’s embeds its stylists and hours. The profile page is one read. Embedding also gives “the ability to update related data in a single atomic write operation”, because in MongoDB “an operation on a single document is atomic.”
The costs come from the same choice. Schema on read stores a misspelt field happily, unless you turn on schema validation. A document has a ceiling: as of 2026-11-29, “the maximum BSON document size is 16 mebibytes”, so a list that grows without bound, like a salon’s reviews, needs its own collection. And a rule across documents needs a multi-document transaction, which “incurs a greater performance cost over single document writes”.
Do you need a document database for this? Often not. PostgreSQL’s jsonb “supports indexing”: a GIN
index searches “for keys or key/value pairs occurring within a large number of jsonb documents”. The
manual still advises documents “have a somewhat fixed structure”.
Gives up: joins, and schema checks unless you add them.
Wide-column: huge writes, read by key in order
Section titled “Wide-column: huge writes, read by key in order”Request 3. The message log is written far more than it is read, never updated, and read one way: newest first, for one customer.
Google’s 2006 Bigtable paper describes this kind of store: “a sparse, distributed, persistent multi-dimensional sorted map”. Wide-column stores such as Bigtable and Cassandra group rows by a partition key, which picks the machine, and keep them sorted by a sort key (Cassandra: a clustering column) inside each partition.
Two mechanisms make it fit. First, the write path. Cassandra records each write in a commit log, its write-ahead log, and in a memtable in memory, then flushes memtables to immutable sorted files called SSTables. Nothing on disk is updated in place, so writes are appends. The cost arrives later: background compaction merges SSTables, so “every write of data in Cassandra is re-written multiple times, known as write amplification”.
Second, the read path, which you design up front. Cassandra’s docs: “data modeling is query-driven”, and since “joins are not supported”, “all required fields (columns) must be grouped together in a single table.”
Here is query-first modelling on the message log. The access pattern is “the last 50 messages for a customer”:
| Role | Column | Why |
|---|---|---|
| Partition key | customer_id |
one customer’s messages sit together |
| Sort key | sent_at, newest first |
“last 50” reads the head of one partition |
| Other columns | business name, template name, status | copied in, because there is no join |
Then the product team adds “every message one business sent yesterday”. This table cannot answer it without reading every partition. The fix is a second table, keyed by business and day, and every message written twice. Cassandra names the trade: “Data duplication and a high write throughput are used to achieve a high read performance.”
Choose the partition key with care. AWS warns against traffic “focused on one part of the database, where they can exceed I/O capacity”: a hot spot, the subject of lesson 3.3.
Gives up: joins, ad hoc queries, and adding a query without adding a table.
Graph: when the links are the data
Section titled “Graph: when the links are the data”Request 4. “Who did Ada refer, and who did they refer?” In tables, each level is a self-join on a
referred_by column. PostgreSQL handles it with WITH RECURSIVE, where a query “can refer to its own
output”; the manual says such queries “are typically used to deal with hierarchical or
tree-structured data.” For a referral tree a few levels deep, that is enough.
The strain comes when most questions are about paths, such as “customers two hops from Ada who booked Tolu”. A graph database stores the links as records of their own. Neo4j’s docs: it “stores data as nodes, relationships, and properties instead of in tables or documents”. A relationship has a start node, an end node, a type and a direction, and can carry properties, such as the date of a referral. Neo4j’s claim is that “graph databases do not use JOINs. Rather, relationships are stored natively alongside the data elements”.
Gives up: in this course’s view, mostly the simplicity of one database, since bookings and money still need tables. If your questions rarely go deeper than two or three hops, a recursive query is cheaper.
Time-series: values that arrive in order
Section titled “Time-series: values that arrive in order”Request 5. Each metric is a number with a timestamp, appended in time order, read as ranges, summed
into buckets (“per minute”), and deleted when old. Prometheus states the model: it “stores all data
as time series: streams of timestamped values belonging to the same metric and the same set of
labeled dimensions”. One series here is bookings_total{city="Lagos"}.
A time-series database lays out storage by time, because almost every question has a time range. Prometheus groups incoming samples “into two-hour blocks”. TimescaleDB, a PostgreSQL extension, “partitions your data into time-based chunks” and “optimizes queries by only scanning relevant time ranges”. Retention becomes cheap: Prometheus removes whole blocks once they are “fully expired”, instead of deleting rows one by one. As of 2026-11-29, it keeps 15 days by default.
Gives up: old detail, which is rolled up or dropped, and speed on any query without a time range.
Vector: nearest by meaning
Section titled “Vector: nearest by meaning”Request 6 matches no keyword. The fix starts outside the database: a model turns text into an embedding. OpenAI’s guide: “An embedding is a vector (list) of floating point numbers. The distance between two vectors measures their relatedness.” Embed each service description once, embed the search text, and return the closest services.
What does the database add? An index for “nearest”. pgvector, a PostgreSQL extension (v0.8.7, tagged
2026-10-01), adds a vector column and distance operators such as <-> (straight-line distance) and
<=> (cosine distance):
SELECT name FROM service ORDER BY embedding <=> :query_embedding LIMIT 5;With no index, pgvector “performs exact nearest neighbor search, which provides perfect recall”: it compares the query with every row, a full table scan again. Recall is the share of the true nearest neighbours that the search returns. An index is fast because it is approximate: it “trades some recall for speed”, and “unlike typical indexes, you will see different results for queries after adding an approximate index.”
One such index is HNSW, from Malkov and Yashunin’s 2016 paper: layers of neighbour graphs, searched from the top layer down, with “logarithmic complexity scaling”. pgvector says it beats its other index, IVFFlat, on the speed-recall trade-off, “but has slower build times and uses more memory.”
A vector database is a store built around such an index; lesson 4.5 asks when you need one.
Gives up: exactness, once indexed. The answer is “probably the closest”.
Before you add a second database
Section titled “Before you add a second database”PostgreSQL covered most of this lesson: jsonb, WITH RECURSIVE, TimescaleDB, pgvector. The lines
blur from the other side too. As of 2026-11-29, Redis lists itself as “a cache, vector database,
document database, streaming engine, and message broker”, and DynamoDB’s quotas page includes vector
indexes.
So a type describes a design, not a product. In this course’s view, a second database must pay for three costs: one more system to run, back up and upgrade; no transaction across the two, so a booking and its copy elsewhere can disagree after a crash; and a team that must know both. Sessions in Redis usually pay their way. A document store for twelve business types usually does not.
Trade-offs
Section titled “Trade-offs”Relational or NoSQL for the core data. Relational gives ad hoc queries, joins and transactions across rows, which is what bookings and money need (lesson 1.5). Its cost is that spreading writes across machines takes work (Part 3). A NoSQL design scales by key, at the cost of knowing your queries up front and maintaining every copy. This course’s suggestion: start relational, and move one workload out when its access pattern is narrow and its rate is measured.
Schema on write or on read. Schema on write catches bad data at the door and makes every change a migration. Schema on read makes changes free and moves the checks into every reader.
Drill 1 — interview question
Section titled “Drill 1 — interview question”“You are designing storage for a salon booking platform: bookings and payments, user sessions, and a log of every reminder sent. SQL or NoSQL? Justify each choice.”
Model answer
Access patterns first. Bookings and payments are read many ways (by customer, stylist, day, status), and rules span rows: no double booking, paid equals owed. That needs ad hoc queries, joins and multi-row transactions: relational.
Sessions are read and written by one key and expire. A key-value store such as Redis fits: get and set by id, a timeout that deletes the key, memory-speed reads. Cost: a second system, and up to a second of writes lost with default append-only logging, which sessions can afford.
The message log is append-only and read as “last N for a customer”. At modest volume, a
PostgreSQL index on (customer_id, sent_at) is enough. At very high volume, a wide-column store with
partition key customer_id and sort key sent_at descending makes writes cheap appends. Cost: each
new query is a new table and another copy of every write.
Close with the cost: no transaction across stores, and more to operate.
Rubric
- Lists access patterns before naming any database — 2
- Keeps bookings and payments relational, citing joins, ad hoc queries and multi-row rules — 2
- Chooses key-value for sessions, with expiry and the durability trade-off — 2
- Designs the message log by its query, with a partition and sort key, and says when it would move — 2
- Names the cost of running more than one database — 2
Total 10. 8 or more is a pass.
Drill 2 — interview question
Section titled “Drill 2 — interview question”The interviewer follows up: “Your message log is in a wide-column store, keyed by customer and time. Now support ‘every message one business sent yesterday’. And the owner wants to fix a typo in a template name across every past message. What happens?”
Model answer
The new query. The table is partitioned by customer, so one business’s messages are spread over
every partition. Add a second table with partition key (business_id, day) and sort key sent_at,
and write each message to both. Adding the day stops one busy business from becoming one huge, hot
partition.
The cost. Two writes per message, twice the storage, and the tables disagree if one write fails, so the application must retry or repair.
The typo. The template name was copied into every row of both tables, because there are no joins. Fixing it means rewriting every copy: lesson 1.4’s update anomaly, accepted on purpose. Better: store a template id and look names up separately, or decide the log records what was sent and never changes.
Rubric
- Explains why the existing partition key cannot serve the query — 2
- Adds a second table keyed for the new query — 2
- Bounds the partition (for example by day) and names the hot-spot risk — 2
- Names the double-write cost and the drift risk — 2
- Connects the typo to the update anomaly and offers a fix — 2
Total 10. 8 or more is a pass.
Drill 3 — hands-on exercise
Section titled “Drill 3 — hands-on exercise”Try three shapes inside one PostgreSQL database, with the pgvector extension installed.
- Create
business (id bigint primary key, profile jsonb). Insert 100,000 profiles of three types with different fields. Predict the plan forWHERE profile @> '{"type": "tailor"}', runEXPLAIN ANALYZE, add a GIN index, and run it again. - Create
customer (id bigint primary key, referred_by bigint)with a referral chain six deep. Write aWITH RECURSIVEquery for everyone below one customer. - Create
service (id bigint primary key, name text, embedding vector(3))with twenty made-up embeddings. Return the five nearest to one vector with<->. Add an HNSW index; compare the answers and the plans. - On paper, design the wide-column table for “last 50 messages for a customer”, then one for “messages one business sent on one day”. Count the writes per message.
Write one sentence per step on what surprised you.
Exit test
Section titled “Exit test”Answer without notes.
- What does a relational database make cheap, and which workload signals make another type worth its cost?
- For key-value, document, wide-column, graph, time-series and vector databases, name the access pattern each makes cheap and one thing each gives up.
- Design the partition key and sort key for “last 50 messages for a customer”. What happens when a second query arrives?
- When is PostgreSQL’s
jsonbenough instead of a document database? When does a graph question outgrowWITH RECURSIVE? - Why can an approximate vector index return different results from an exact search, and when is that acceptable?
Further reading
Section titled “Further reading”- Giuseppe DeCandia and others, Dynamo: Amazon’s Highly Available Key-value Store (2007) — https://www.allthingsdistributed.com/files/amazon-dynamo-sosp2007.pdf.
- Fay Chang and others, Bigtable: A Distributed Storage System for Structured Data (2006) — https://static.googleusercontent.com/media/research.google.com/en//archive/bigtable-osdi06.pdf.
- AWS, NoSQL design for DynamoDB — https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/bp-general-nosql-design.html.
- Apache Cassandra 5.0, Data modeling — https://cassandra.apache.org/doc/5.0/cassandra/developing/data-modeling/intro.html; Storage engine — https://cassandra.apache.org/doc/5.0/cassandra/architecture/storage-engine.html.
- MongoDB manual, Data Modeling — https://www.mongodb.com/docs/manual/data-modeling/.
- Redis, Persistence — https://redis.io/docs/latest/operate/oss_and_stack/management/persistence/.
- Neo4j, What is a graph database — https://neo4j.com/docs/getting-started/graph-database/.
- Prometheus, Data model — https://prometheus.io/docs/concepts/data_model/; Storage — https://prometheus.io/docs/prometheus/latest/storage/.
- Yu. A. Malkov and D. A. Yashunin, Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs (2016) — https://arxiv.org/abs/1603.09320.
- pgvector README (v0.8.7) — https://github.com/pgvector/pgvector; TimescaleDB README — https://github.com/timescale/timescaledb.
- OpenAI, Embeddings guide — https://developers.openai.com/api/docs/guides/embeddings.
- PostgreSQL 19, JSON Types — https://www.postgresql.org/docs/current/datatype-json.html; WITH Queries — https://www.postgresql.org/docs/current/queries-with.html. All checked 2026-11-29.