Skip to content
Draft — this lesson has not been reviewed yet. Its facts are sourced, but read it with a critical eye.

SQL vs NoSQL and database types

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.

  1. 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.
  2. Business profiles. A salon lists hours and stylists, a tailor the measurements she takes. Each new kind of business is a migration.
  3. 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”.
  4. Referrals. “Who did Ada refer, who did they refer, and so on down?” Each level is one more join.
  5. Metrics. Bookings per minute, per city, kept for a month and drawn as a line.
  6. 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.

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.

The six requests as one decision. Each arrow is the main question; each box is what that type gives up.

any question, joins,
rules across rows

get or set
by one key

whole object by id,
shape varies

huge append-only writes,
read by key in order

follow links
many hops deep

values over time,
ranges and roll-ups

nearest by
meaning

List the access patterns
and their rates

What is the
main question?

Relational
gives up: easy scaling
of writes across machines

Key-value
gives up: every other query

Document
gives up: joins,
schema checks by default

Wide-column
gives up: joins,
a new query needs a new table

Graph
gives up: one database
for everything

Time-series
gives up: old detail,
queries that ignore time

Vector
gives up: exact answers
once indexed

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.

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”.

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.

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.

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.

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”.

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.

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.

“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.

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.

Try three shapes inside one PostgreSQL database, with the pgvector extension installed.

  1. Create business (id bigint primary key, profile jsonb). Insert 100,000 profiles of three types with different fields. Predict the plan for WHERE profile @> '{"type": "tailor"}', run EXPLAIN ANALYZE, add a GIN index, and run it again.
  2. Create customer (id bigint primary key, referred_by bigint) with a referral chain six deep. Write a WITH RECURSIVE query for everyone below one customer.
  3. 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.
  4. 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.

Answer without notes.

  1. What does a relational database make cheap, and which workload signals make another type worth its cost?
  2. 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.
  3. Design the partition key and sort key for “last 50 messages for a customer”. What happens when a second query arrives?
  4. When is PostgreSQL’s jsonb enough instead of a document database? When does a graph question outgrow WITH RECURSIVE?
  5. Why can an approximate vector index return different results from an exact search, and when is that acceptable?