SQL vs NoSQL: relational, key-value, document, wide-column, graph
Choose a data model and database family for an access pattern.
By Invicly Tech, , in System Design Deep Dive. About 12 minutes to read.
In short
Relational databases offer schemas, joins and transactions; NoSQL families trade some of that for scale or flexibility. Pick the data model that matches your access patterns, not the trendiest technology.
Explained simply
A database is a program that stores data safely and finds it again quickly. There are several families, and each one is shaped around a different way of asking for data. Relational databases (SQL) store rows in tables and let you ask almost any question. NoSQL is a loose name for everything else: key-value, document, wide-column and graph databases.
A relational database is like a well-organised spreadsheet with strict columns. You store each fact once and connect tables with IDs. You can join tables, filter on any column and wrap many changes in one transaction that either fully happens or not at all. That makes it the safe default for orders, payments and user accounts.
NoSQL databases give up some of that freedom to win something else. A key-value store is a giant dictionary: give a key, get a value, very fast. A document store keeps one JSON-like object per record. A wide-column store spreads huge write volumes across many machines. A graph database is built for following links between things, like friends of friends.
The real question is never SQL or NoSQL in general. It is: what are the exact queries my app runs, how much data, how many writes per second, and what must never go wrong? Answer those first, then pick the family that makes those queries cheap.
Press Play on a diagram to walk through it one step at a time.
- Relational
- PostgreSQL, MySQL
- Joins and ACID transactions
- Key-value
- Redis, DynamoDB
- Fast lookups by key
- Document
- MongoDB
- Flexible JSON documents
- Wide-column
- Cassandra, Bigtable
- Massive writes, partition keys
- Graph
- Neo4j
- Relationship traversals
- Fixed schema, normalised
- Joins and ACID transactions
- Flexible ad-hoc queries
- Scales up, sharding is manual
- Schema-flexible or denormalised
- Designed around known queries
- Scales out horizontally
- Weaker or tunable consistency
- orders, order_items, products tables
- Joined by IDs at read time
- Each fact stored once
- Any new query is easy
- One order document
- Items and prices embedded
- Read in one fetch
- Product name copied in
- Key: order#123
- Value: the whole order blob
- Only lookup by order ID
- Other queries need another table
In depth
Relational databases: more scalable than people think
PostgreSQL and MySQL handle far more than most products ever need. One well-tuned server with fast SSDs can serve tens of thousands of simple queries per second and store several terabytes. You add read replicas to spread reads, and a cache in front for hot data.
Modern relational databases also blur the line with NoSQL. PostgreSQL has a JSONB column type that stores JSON documents and can index them with a GIN index, so you can keep flexible attributes next to strict columns. Extensions like Citus, and databases like CockroachDB, YugabyteDB and Google Spanner, shard SQL tables across many machines while keeping transactions.
The real limit appears when one server can no longer absorb the writes, or when the data is too big for one disk. That is usually much later than teams fear.
- Start relational unless you can name the access pattern it cannot serve
- JSONB plus a GIN index covers many document-style needs
- Distributed SQL keeps transactions while scaling out, at a latency cost
Key-value and document stores
A key-value store only understands one operation well: look up a value by its exact key. Redis keeps everything in memory, so reads take well under a millisecond, which suits sessions, carts, counters and caches. DynamoDB stores data on disk across many partitions and returns items in single-digit milliseconds at almost any scale, with a 400 KB limit per item.
A document store such as MongoDB understands the inside of each value. Each record is a JSON-like document (BSON in MongoDB, up to 16 MB each), and you can query and index fields inside it. This fits data that is read and written as one unit, like a product with a varying list of attributes, or a user profile with nested settings.
The catch: data split across many documents has no cheap join, so you embed related data that is read together and accept some duplication.
Wide-column stores: built for huge write volumes
Cassandra, ScyllaDB, HBase and Google Bigtable store rows grouped into partitions. In Cassandra, the primary key has two parts: the partition key decides which nodes hold the row, and the clustering columns sort rows inside that partition. Reading one partition in clustering order is very fast. Reading across many partitions is slow or not allowed.
Writes go to an append-only commit log and an in-memory table, so they are cheap, and every node can accept them. That is why these stores suit chat messages, sensor readings, activity logs and time series, where you write constantly and read a slice of one partition.
The rule is query-first modelling: you design one table per query and duplicate data between tables. Keep each partition bounded (a common guideline is under about 100 MB), for example by adding a month to the partition key.
- One record = one nested document
- Index any field inside it
- Good for objects read as a whole
- Flexible, per-record shape
- Partition key picks the nodes
- Clustering columns sort rows
- Good for slices of one partition
- One table per query, data duplicated
Graph databases: when relationships are the data
In a graph database like Neo4j or Amazon Neptune, data is stored as nodes (things) and edges (relationships), and each node points directly to its neighbours. Following a relationship costs about the same no matter how big the whole graph is.
In SQL, a question like friends of friends who like the same band needs several self-joins. Each extra hop multiplies the work, and queries get slow and hard to write. In a graph query language like Cypher, the same question is a short pattern: MATCH (a)-[:FRIEND]->()-[:FRIEND]->(c).
Graphs fit recommendations, fraud rings (accounts sharing cards and devices), network maps and permission hierarchies. They are a poor fit for simple lookups or big aggregate reports, so they usually sit beside a main database rather than replace it.
Matching a database to an access pattern
Write down your top queries first, with expected volume. Then ask a few questions in order. Do you need multi-row transactions with strict rules, like moving money or reserving stock? Use relational. Is it lookup by one key at huge scale with no joins? Key-value. Do you write constantly and read recent items for one owner? Wide-column. Are multi-hop relationships the main query? Graph. Do you need full-text search? Add a search engine like Elasticsearch next to your main store.
Most real systems are polyglot: they use two or three stores, each for what it is good at, and keep them in sync with events. Each extra database adds operations work, backups and failure modes, so add one only when the main store clearly cannot do the job.
- 1List top queries
With reads and writes per second
- 2Need transactions?
Yes: start relational
- 3Only lookup by key?
Yes: key-value store
- 4Write-heavy timelines?
Yes: wide-column store
- 5Multi-hop links?
Yes: graph database
Learn it in 4 short steps
About 45m each. Track them with a timer in your plan.
- 1Compare relational and key-value stores~45m
- 2Compare document and wide-column stores~45m
- 3Know when a graph database fits~45m
- 4Match a database to an access pattern~45m
Key points
- Default to a relational database unless a clear need says otherwise.
- Key-value stores excel at simple lookups like sessions and carts.
- Wide-column stores suit huge write volumes like messages or time series.
- Graph databases fit queries about multi-hop relationships.
- In NoSQL you model tables around queries, often duplicating data.
Key terms
Tap a card to flip it. 0/5 known
Examples
An online shop that uses three stores
Step 1: list the access patterns. Checkout must reduce stock and create an order atomically, so orders and inventory live in PostgreSQL. Step 2: shopping carts are read and written on every page view and are fine to lose after a few days, so they go in Redis with a TTL (time to live). Step 3: product search needs typo tolerance and filters, so products are copied into Elasticsearch, which is updated from change events. PostgreSQL stays the source of truth. The checkout transaction below never sells stock that does not exist.
BEGIN;
UPDATE inventory SET qty = qty - 1
WHERE sku = 'MUG-01' AND qty > 0;
-- the app checks that 1 row was updated, else ROLLBACK
INSERT INTO orders (user_id, sku, price_cents)
VALUES (42, 'MUG-01', 1299);
COMMIT;Storing chat messages in Cassandra
The main query is: show the latest 50 messages of one conversation, then scroll back. Step 1: make conversation_id the partition key so one conversation lives together. Step 2: make message_id (a time-based UUID) the clustering column, sorted newest first. Step 3: the query reads one partition in order, which is fast at any scale. Step 4: for very busy group chats, add a bucket such as the month to the partition key so no partition grows forever.
CREATE TABLE messages (
conversation_id uuid,
message_id timeuuid,
sender_id uuid,
body text,
PRIMARY KEY ((conversation_id), message_id)
) WITH CLUSTERING ORDER BY (message_id DESC);
SELECT * FROM messages
WHERE conversation_id = 6a1f0c3e-2b4d-4e8a-9c1f-0d2e3f4a5b6c
LIMIT 50;Quick reference
- Default to PostgreSQL or MySQL; move to NoSQL for a named access pattern, not for fashion
- Money, stock, bookings: you want ACID transactions
- Sessions, carts, counters, caches: key-value (Redis, DynamoDB)
- Chat, events, time series at huge write rates: wide-column (Cassandra, Bigtable)
- Friends of friends, fraud rings, recommendations: graph (Neo4j, Neptune)
- In NoSQL, design one table per query and accept duplicated data
- DynamoDB item limit: 400 KB; MongoDB document limit: 16 MB
- Full-text search goes in a search engine kept in sync with the main database
Common mistakes
- Choosing NoSQL for scale the product will never reach.
- Modelling Cassandra tables like relational tables and then needing joins.
- Forgetting transactions when money or inventory is involved.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Pick a database family for each workload and give one reason: (a) login sessions, (b) invoices, (c) IoT temperature readings every second from 1 million devices, (d) a 'people you may know' feature.
- Exercise 2medium
Design a DynamoDB table for two queries: get an order by ID, and list one customer's orders newest first. Name the keys and any index.
- Exercise 3hard
A social app stores follows in PostgreSQL (follows(follower_id, followee_id)). Write the 'suggest people followed by people I follow' query in Cypher, and explain when moving this feature to a graph database is worth it.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Is NoSQL faster than SQL?
- Not in general. A NoSQL store is fast for the queries it was modelled for and slow or unable to run others. A relational database with the right indexes is fast for a wide range of queries.
- Can PostgreSQL replace MongoDB?
- Often, yes. A JSONB column with a GIN index stores and queries JSON documents well. MongoDB still has an edge in built-in sharding and developer tooling for document-first apps.
- Does NoSQL mean no schema?
- No. The database may not enforce a schema, but your code still expects a shape. You end up managing the schema in the application instead.
- What does polyglot persistence mean?
- Using more than one kind of database in one system, each for the queries it does best, such as PostgreSQL for orders and Redis for sessions.