SQL vs NoSQL and the CAP theorem
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A teammate says ShopLite should move to NoSQL because it scales. Is that true? The answer depends on the shape of the data, the queries, and what must stay correct when servers lose contact.
Your turn: move to NoSQL?
The team wants to "move everything to NoSQL". Before reading on, decide for ShopLite:
- Which data must stay in MySQL because several changes have to succeed or fail together?
- Which data is only ever read by one key, such as a login session?
- Two data centres lose contact but both keep selling. What happens to a stock count?
The four NoSQL families
NoSQL is a loose name for databases that do not use tables, joins and SQL as their main model; each family (key-value, document, wide-column, graph) is built for one data shape and one kind of query.
Each NoSQL family stores data in its own shape. This program models all four, plus a relational example, with plain Java collections.
Example 1 · The four NoSQL data shapes, modelled with Java collections
import java.util.HashMap;import java.util.Map;import java.util.Set;import java.util.TreeMap;
public class NoSqlShapesDemo { public static void main(String[] args) { Map<String, String> sessions = new HashMap<>(); sessions.put("session:7f3a", "{\"userId\":2,\"cart\":[6,9]}"); System.out.println("key-value GET session:7f3a -> " + sessions.get("session:7f3a"));
Map<String, Object> phone = Map.of("sku", "MOB-RN13", "name", "Redmi Note 13 5G", "specs", Map.of("ram", "8GB", "storage", "256GB")); Map<String, Object> book = Map.of("sku", "BK-CLEAN", "name", "Clean Code", "specs", Map.of("author", "Robert C. Martin", "pages", 464)); System.out.println("document " + phone.get("sku") + " specs " + new TreeMap<>((Map<?, ?>) phone.get("specs")) + " | " + book.get("sku") + " specs " + new TreeMap<>((Map<?, ?>) book.get("specs")));
Map<String, TreeMap<String, Integer>> viewsByDay = new HashMap<>(); viewsByDay.computeIfAbsent("product:1", k -> new TreeMap<>()).put("2026-10-01", 1840); viewsByDay.get("product:1").put("2026-10-02", 2210); viewsByDay.get("product:1").put("2026-10-03", 1975); System.out.println("wide-column product:1 views " + viewsByDay.get("product:1"));
Map<String, Set<String>> boughtWith = Map.of( "Redmi Note 13 5G", Set.of("boAt Airdopes 141"), "boAt Airdopes 141", Set.of("Mi Power Bank 20000mAh")); String start = "Redmi Note 13 5G"; for (String next : boughtWith.get(start)) { System.out.println("graph " + start + " -> " + next + " -> " + boughtWith.getOrDefault(next, Set.of())); } System.out.println("relational orders JOIN order_items JOIN products: rows, keys, constraints, transactions"); }}key-value GET session:7f3a -> {"userId":2,"cart":[6,9]}
document MOB-RN13 specs {ram=8GB, storage=256GB} | BK-CLEAN specs {author=Robert C. Martin, pages=464}
wide-column product:1 views {2026-10-01=1840, 2026-10-02=2210, 2026-10-03=1975}
graph Redmi Note 13 5G -> boAt Airdopes 141 -> [Mi Power Bank 20000mAh]
relational orders JOIN order_items JOIN products: rows, keys, constraints, transactionsWhat this code does
- The key-value store only answers "give me the value for this key". The document store keeps different
specsfields for a phone and a book in the same collection. - The wide-column row keeps columns sorted by date, ready for time ranges, and the graph answers a two-step "bought with" question by following links.
Each family stores data in a different shape:
- Key-value (Redis, Amazon DynamoDB): a key maps to a value, read only by key. Use case: sessions, carts, caches, counters.
- Document (MongoDB): each item is a nested JSON-like document, and items in one collection can have different fields. Use case: product specs that differ by category.
- Wide-column (Apache Cassandra, HBase): a row key with many sorted columns, built for huge write volumes spread over many servers. Use case: view and click events by time.
- Graph (Neo4j): nodes and relationships, queried by following links. Use case: "customers who bought this also bought", fraud rings.
Predict the output
Which family fits?
Pick the best family for each need.
Round 1 of 3
Choosing for the right reasons
Choose a database from four questions, not from fashion. This program prints the choice for five ShopLite data sets.
Example 2 · A simple decision guide for ShopLite's data sets
import java.util.List;
public class ChooseStoreDemo { record DataSet(String name, boolean needsMultiRowTransactions, boolean relationsAndJoins, boolean onlyLookupByKey, boolean flexibleFields, boolean hugeAppendOnlyWrites) { }
static String choose(DataSet d) { if (d.needsMultiRowTransactions() || d.relationsAndJoins()) { return "relational (MySQL)"; } if (d.onlyLookupByKey()) { return "key-value (Redis / DynamoDB)"; } if (d.hugeAppendOnlyWrites()) { return "wide-column (Cassandra)"; } if (d.flexibleFields()) { return "document (MongoDB), or a JSON column in MySQL"; } return "relational (MySQL): the safe default"; }
public static void main(String[] args) { List<DataSet> sets = List.of( new DataSet("Orders + items + stock", true, true, false, false, false), new DataSet("Login sessions / carts", false, false, true, false, false), new DataSet("Product specs per category", false, false, false, true, false), new DataSet("Click and view events", false, false, false, false, true), new DataSet("Customer addresses", false, true, false, false, false)); for (DataSet d : sets) { System.out.printf("%-28s -> %s%n", d.name(), choose(d)); } }}Orders + items + stock -> relational (MySQL) Login sessions / carts -> key-value (Redis / DynamoDB) Product specs per category -> document (MongoDB), or a JSON column in MySQL Click and view events -> wide-column (Cassandra) Customer addresses -> relational (MySQL)
What this code does
- Transactions or relations come first: anything that needs them stays relational.
- Only data with one clear access pattern (key lookups, flexible specs, a firehose of events) goes to a specialised store.
The four questions: data shape (tables with relations, nested documents, a simple key to value, or a graph?), query patterns (key lookups only, or filters, joins and reports?), consistency needs (must several changes succeed or fail together, and must every reader see the latest value?) and team skills (who runs, backs up and debugs it at 2 a.m.?).
Wrong reasons are "MySQL does not scale" (it scales a long way with indexes, caching, replicas and sharding) and "NoSQL has no schema" (the schema moves into the code, and every reader must handle every old shape). The relational database is the safe default; add another store when one data set clearly fits it better.
Why ShopLite orders stay in MySQL
A transaction is a group of database changes that either all succeed together or are all undone, so the data is never left half-changed.
Placing an order changes several rows. This program fails an order for lack of stock, with and without a transaction.
Example 3 · Why an order needs a transaction
import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;
public class OrderTransactionDemo { static Map<String, Integer> stock = new HashMap<>(Map.of("MOB-IP15", 8, "ACC-AD141", 1)); static List<String> orders = new ArrayList<>();
static void placeOrderInTransaction(String orderId, Map<String, Integer> items) { Map<String, Integer> stockCopy = new HashMap<>(stock); for (Map.Entry<String, Integer> item : items.entrySet()) { int left = stockCopy.get(item.getKey()) - item.getValue(); if (left < 0) { System.out.println(" " + orderId + ": ROLLBACK, not enough " + item.getKey()); return; } stockCopy.put(item.getKey(), left); } stock = stockCopy; orders.add(orderId); System.out.println(" " + orderId + ": COMMIT"); }
static void placeOrderWithoutTransaction(String orderId, Map<String, Integer> items) { for (Map.Entry<String, Integer> item : items.entrySet()) { int left = stock.get(item.getKey()) - item.getValue(); if (left < 0) { System.out.println(" " + orderId + ": failed on " + item.getKey() + ", earlier stock changes stay"); return; } stock.put(item.getKey(), left); } orders.add(orderId); }
public static void main(String[] args) { Map<String, Integer> cart = new java.util.LinkedHashMap<>(); cart.put("MOB-IP15", 1); cart.put("ACC-AD141", 2);
System.out.println("With a transaction:"); placeOrderInTransaction("order-77", cart); System.out.println(" stock " + new java.util.TreeMap<>(stock) + ", orders " + orders);
System.out.println("Without a transaction:"); placeOrderWithoutTransaction("order-78", cart); System.out.println(" stock " + new java.util.TreeMap<>(stock) + ", orders " + orders + " <- an iPhone vanished"); }}With a transaction:
order-77: ROLLBACK, not enough ACC-AD141
stock {ACC-AD141=1, MOB-IP15=8}, orders []
Without a transaction:
order-78: failed on ACC-AD141, earlier stock changes stay
stock {ACC-AD141=1, MOB-IP15=7}, orders [] <- an iPhone vanishedWhat this code does
- With a transaction, the stock change for the iPhone is made on a private copy and thrown away when the earbuds are short: nothing changes.
- Without one, the iPhone's stock drops to 7 before the failure and stays there, although no order exists. Real document stores offer multi-document transactions too, but they are the default in a relational database.
Placing an order inserts the order, inserts its items and reduces stock for each product. If anything fails, such as not enough stock, nothing may be kept. A relational transaction gives exactly that, plus foreign keys and constraints that stop impossible data, and SQL for the reports the business will ask for.
Other stores can still help around the edges: Redis for sessions, carts and caches; a document store or a MySQL JSON column for product specs; a wide-column or analytics store for the click stream; a search engine for product search. This mix is called polyglot persistence: several stores, each for what it does best, with MySQL as the source of truth for money and orders.
Order of execution
One order, one transaction
Put the steps of a safe order in sequence.
CAP in plain words
The CAP theorem says that when a replicated database is cut in two by a network failure, it must choose between consistency (never return stale or wrong data) and availability (always answer).
Two data centres lose contact and a customer buys the last units. This program compares a CP system with an AP system.
Example 4 · A network partition: CP refuses, AP diverges
import java.util.HashMap;import java.util.Map;
class ReplicaNode { final String name; final Map<String, Integer> data = new HashMap<>(); final Map<String, Long> writtenAt = new HashMap<>();
ReplicaNode(String name) { this.name = name; }}
public class CapPartitionDemo { static boolean partitioned = false;
static String writeCP(ReplicaNode local, ReplicaNode remote, String key, int value) { if (partitioned) { return local.name + ": ERROR, cannot reach " + remote.name + " (unavailable, but never wrong)"; } local.data.put(key, value); remote.data.put(key, value); return local.name + ": OK " + key + "=" + value + " on both"; }
static String writeAP(ReplicaNode local, ReplicaNode remote, String key, int value, long time) { local.data.put(key, value); local.writtenAt.put(key, time); if (!partitioned) { remote.data.put(key, value); remote.writtenAt.put(key, time); } return local.name + ": OK " + key + "=" + value + (partitioned ? " (only here for now)" : " on both"); }
public static void main(String[] args) { ReplicaNode mumbai = new ReplicaNode("mumbai"); ReplicaNode chennai = new ReplicaNode("chennai");
System.out.println("CP system:"); System.out.println(" " + writeCP(mumbai, chennai, "stock:5", 5)); partitioned = true; System.out.println(" " + writeCP(chennai, mumbai, "stock:5", 4));
partitioned = false; System.out.println("AP system:"); System.out.println(" " + writeAP(mumbai, chennai, "stock:5", 5, 100)); partitioned = true; System.out.println(" " + writeAP(mumbai, chennai, "stock:5", 4, 200)); System.out.println(" " + writeAP(chennai, mumbai, "stock:5", 3, 210)); System.out.println(" during the partition: mumbai says " + mumbai.data.get("stock:5") + ", chennai says " + chennai.data.get("stock:5"));
partitioned = false; boolean chennaiNewer = chennai.writtenAt.get("stock:5") > mumbai.writtenAt.get("stock:5"); int winner = chennaiNewer ? chennai.data.get("stock:5") : mumbai.data.get("stock:5"); mumbai.data.put("stock:5", winner); chennai.data.put("stock:5", winner); System.out.println(" after healing (last write wins): stock:5 = " + winner + ", but 3 units were sold, so the right answer is 2"); }}CP system: mumbai: OK stock:5=5 on both chennai: ERROR, cannot reach mumbai (unavailable, but never wrong) AP system: mumbai: OK stock:5=5 on both mumbai: OK stock:5=4 (only here for now) chennai: OK stock:5=3 (only here for now) during the partition: mumbai says 4, chennai says 3 after healing (last write wins): stock:5 = 3, but 3 units were sold, so the right answer is 2
What this code does
- The CP system rejects Chennai's write because it cannot reach Mumbai: unavailable, but never wrong.
- The AP system accepts both sides' sales. After healing, last-write-wins keeps Chennai's 3, but 3 units were sold from 5, so the right stock is 2: one update was lost.
A network partition is when the servers holding the copies cannot talk to each other but are still running. During one, a CP system refuses some requests so it is never wrong. An AP system keeps answering on both sides and fixes the differences after the network heals, which can lose or merge updates.
Partitions are not optional in real networks, so the real choice is C or A while a partition lasts; when there is no partition, a system can have both.
Predict the output
CP or AP?
During a network partition, what does each system do?
Round 1 of 2
Eventual consistency, PACELC and common myths
Eventual consistency means that if writes stop, all copies of the data become the same after some time, though readers may briefly see different values.
A new rating reaches the three copies one at a time. This program shows the copies agreeing, then tests quorum settings.
Example 5 · Eventual consistency and quorums
import java.util.ArrayList;import java.util.List;
public class EventualConsistencyDemo { record Versioned(int version, String value) { }
public static void main(String[] args) { List<Versioned> replicas = new ArrayList<>(List.of( new Versioned(1, "4.2 stars"), new Versioned(1, "4.2 stars"), new Versioned(1, "4.2 stars")));
// A write reaches replica 0 first; the others get it one step at a time replicas.set(0, new Versioned(2, "4.3 stars")); for (int step = 0; step <= 2; step++) { if (step > 0) { replicas.set(step, replicas.get(0)); // the change spreads } System.out.println("step " + step + ": " + replicas.stream().map(Versioned::value).toList()); }
// Quorums: N = 3 copies, a write waits for W, a read asks R and keeps the newest version int n = 3; int[][] settings = {{1, 1}, {2, 1}, {2, 2}, {3, 1}}; for (int[] s : settings) { int w = s[0]; int r = s[1]; System.out.printf("N=%d W=%d R=%d -> %s%n", n, w, r, r + w > n ? "every read overlaps the last write: latest value" : "a read may miss the last write"); } }}step 0: [4.3 stars, 4.2 stars, 4.2 stars] step 1: [4.3 stars, 4.3 stars, 4.2 stars] step 2: [4.3 stars, 4.3 stars, 4.3 stars] N=3 W=1 R=1 -> a read may miss the last write N=3 W=2 R=1 -> a read may miss the last write N=3 W=2 R=2 -> every read overlaps the last write: latest value N=3 W=3 R=1 -> every read overlaps the last write: latest value
What this code does
- The new rating reaches one copy first and the others step by step: for a moment, readers can see different values, then all agree.
- With N = 3, W = 2 and R = 2, any read set overlaps any write set, so a read always includes the newest version.
A quorum system stores a value on N nodes; a write waits for W of them and a read asks R of them. When R + W > N, every read overlaps the latest write. PACELC extends CAP: if there is a Partition, choose A or C; Else, choose lower Latency or stronger Consistency, because even on a healthy network waiting for more copies is slower.
Common myths:
- "Pick any 2 of C, A and P": you cannot give up partitions; you choose C or A during one.
- "NoSQL means no consistency": many NoSQL stores offer tunable or strong consistency.
- "SQL cannot scale": it scales far with replicas, caching and sharding; writes are harder.
- "MySQL is CA": a replicated MySQL setup also faces partitions and must choose.
Next step
Check your understanding
12 quick questions