TExcelTAD
Home › System Design › SQL vs NoSQL

SQL vs NoSQL

Choosing a database is one of the most consequential decisions in a design, because data outlives code. The two broad families are relational (SQL) databases and the many NoSQL models that grew up around web-scale workloads. Neither is "better": each makes different things easy.

Relational (PostgreSQL, MySQL, SQL Server) NoSQL (MongoDB, Cassandra, DynamoDB, Redis, Neo4j)
Data model Tables with rows and typed columns, relations by foreign keys Documents, key-value pairs, wide columns or graphs
Schema Defined up front, enforced by the DB Flexible; enforced by the application (or optional validation)
Queries SQL: joins, aggregates, ad-hoc questions Usually by key or a few planned access patterns
Transactions Multi-row ACID transactions are standard Often single-item or single-partition; multi-item varies
Scaling Vertical first; read replicas; sharding is extra work Many are designed to shard horizontally from the start
Best when Data is relational, correctness matters, queries vary Huge scale, simple access patterns, flexible or nested data

The relational model

Data is normalised into tables, and queries join them back together. Python's built-in sqlite3 module gives us a real SQL database to try:

python · try it yourself
import sqlite3

db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE users  (id INTEGER PRIMARY KEY, name TEXT NOT NULL);
CREATE TABLE orders (id INTEGER PRIMARY KEY, user_id INTEGER REFERENCES users(id),
                     total_cents INTEGER NOT NULL);
INSERT INTO users  VALUES (1, 'Ada'), (2, 'Grace'), (3, 'Linus');
INSERT INTO orders VALUES (10, 1, 2500), (11, 1, 1200), (12, 2, 9900);
""")

query = """
SELECT u.name, COUNT(o.id) AS orders, COALESCE(SUM(o.total_cents), 0) / 100.0 AS spent
FROM users u LEFT JOIN orders o ON o.user_id = u.id
GROUP BY u.id ORDER BY spent DESC
"""
for row in db.execute(query):
    print(row)
('Grace', 1, 99.0)
('Ada', 2, 37.0)
('Linus', 0, 0.0)

This query was never planned when the tables were designed, and SQL answers it anyway. That flexibility, plus transactions and constraints, is why a relational database is the default choice for most new systems.

The NoSQL families

Family Shape Examples Typical use
Key-value key -> opaque value Redis, DynamoDB, Memcached Sessions, caches, counters, feature flags
Document key -> JSON-like document MongoDB, Couchbase, Firestore Product catalogues, user profiles, CMS content
Wide-column partition key -> sorted rows of columns Cassandra, ScyllaDB, HBase, Bigtable Time series, messages, huge write volumes
Graph Nodes and edges with properties Neo4j, Neptune Social graphs, recommendations, fraud rings

Modelling for access patterns

NoSQL design starts from the queries, not from the entities. In a document store you usually denormalise: store together what is read together, so one key lookup returns the whole page.

python · try it yourself
import json

# One document per order, with the items and a copy of the customer's name
orders = {
    "order:10": {"user": {"id": 1, "name": "Ada"}, "status": "shipped",
                 "items": [{"sku": "BOOK-7", "qty": 1, "cents": 1800},
                           {"sku": "PEN-2", "qty": 2, "cents": 350}]},
}

def order_page(order_id):                      # one read, no joins
    doc = orders[order_id]
    total = sum(i["qty"] * i["cents"] for i in doc["items"])
    return f"{doc['user']['name']}: {len(doc['items'])} lines, {total / 100:.2f}, {doc['status']}"

print(order_page("order:10"))
print(json.dumps(orders["order:10"]["items"][0]))
Ada: 2 lines, 25.00, shipped
{"sku": "BOOK-7", "qty": 1, "cents": 1800}

The price of denormalisation: if Ada changes her name, every document that copied it must be updated (or you accept old names on old orders, which for orders is actually correct).

A wide-column store such as Cassandra organises data by partition key and keeps rows within a partition sorted by a clustering key. "Latest 3 messages of a chat" becomes one sequential read of one partition:

python · try it yourself
from collections import defaultdict
import bisect

table = defaultdict(list)          # partition key -> rows sorted by clustering key

def insert(chat_id, msg_id, text):
    bisect.insort(table[chat_id], (msg_id, text))

for msg_id, chat, text in [(101, "chat:a", "hi"), (102, "chat:b", "yo"), (103, "chat:a", "lunch?"),
                           (104, "chat:a", "sure"), (105, "chat:a", "12:30"), (106, "chat:b", "ok")]:
    insert(chat, msg_id, text)

def latest(chat_id, n):            # one partition, read from the end
    return table[chat_id][-n:][::-1]

print(latest("chat:a", 3))
print("partitions:", sorted(table))
[(105, '12:30'), (104, 'sure'), (103, 'lunch?')]
partitions: ['chat:a', 'chat:b']

How to choose

  1. Start with a relational database unless you have a concrete reason not to. PostgreSQL handles far more load than most products ever reach, and it also stores JSON documents.
  2. Pick a key-value or wide-column store when you need very high write throughput or data sizes that require easy horizontal partitioning, and your access patterns are known.
  3. Pick a document store when records are self-contained, nested and read as a whole, and their shape varies.
  4. Pick a graph database when the questions are about paths and relationships many hops deep.
  5. Use several (polyglot persistence): orders in PostgreSQL, sessions in Redis, search in Elasticsearch, events in Kafka.

Note: "NoSQL scales, SQL doesn't" is a myth. Sharded MySQL runs some of the largest sites in the world, and NewSQL systems (Spanner, CockroachDB, YugabyteDB) offer SQL with automatic sharding. The real difference is which operations are cheap.

Test yourself

Which is the strongest reason to choose a relational database?

  1. Data has no relationships
  2. You need multi-row transactions and flexible ad-hoc queries
  3. You only ever look up values by key
  4. You want to avoid schemas

What does denormalising data in a document store buy you?

  1. Smaller storage
  2. Reading a whole page with a single lookup, without joins
  3. Automatic consistency of copied fields
  4. Stronger transactions

In a wide-column store, what decides which node stores a row?

  1. The clustering key
  2. The partition key
  3. The column names
  4. The insertion time