Relational (SQL) databases store data in tables with a fixed schema, let you ask arbitrary questions with SQL joins and aggregations, and protect invariants with ACID transactions. NoSQL is an umbrella for several other data models (key-value, document, wide-column, graph, plus specialized time-series and search engines) that trade some of those features for horizontal scale, flexible schemas or a shape that matches a specific access pattern. The useful question is never "SQL or NoSQL?" but "which data model and which guarantees do my access patterns need?"
Think of it like
A library vs specialist shops
A relational database is a well-run library with a card catalog: every book is shelved by strict rules, and a librarian can answer any cross-referenced question you think of. NoSQL stores are specialist shops. A coat check (key-value) hands back exactly what you gave it, instantly, if you have the ticket. A filing cabinet (document) keeps everything about one customer in one folder. A corkboard with pins and string (graph) makes the connections themselves the point.
The relational model
Proposed by E. F. Codd in 1970, the relational model stores data as tables (relations) of rows with typed columns. Each row has a primary key; foreign keys reference rows in other tables. SQL is declarative: you describe the result you want, and the query planner works out how to get it, using indexes (see Database Indexing).
CREATE TABLE users (
id BIGINT PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE,
name VARCHAR(100) NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE orders (
id BIGINT PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users(id),
status VARCHAR(20) NOT NULL,
total_cents INTEGER NOT NULL CHECK (total_cents >= 0),
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
-- Who were our top 10 customers last month? (Nobody planned for this query.)
SELECT u.name, SUM(o.total_cents) / 100.0 AS spent
FROM users u
JOIN orders o ON o.user_id = u.id
WHERE o.status = 'paid'
AND o.created_at >= DATE '2026-09-01'
AND o.created_at < DATE '2026-10-01'
GROUP BY u.id, u.name
ORDER BY spent DESC
LIMIT 10;Normalization and joins
Normalization stores each fact exactly once, so updating a customer's email touches one row, not every order they ever placed. The price is that reads must join tables back together. Denormalization deliberately duplicates data to make reads cheaper, at the cost of keeping copies in sync on writes.
- 1NF
- Every column holds a single atomic value: no lists of phone numbers in one cell.
- 2NF
- 1NF, and every non-key column depends on the whole primary key, not part of a composite key.
- 3NF
- 2NF, and non-key columns depend only on the key, not on other non-key columns (no storing
cityalongsidezip_codethat determines it). - Denormalization
- Intentionally duplicating data (an
order_counton users, a copied product name on order lines) to avoid joins on hot read paths.
ACID transactions
- Atomicity
- All statements in a transaction take effect, or none do.
- Consistency
- Constraints (foreign keys, CHECKs, uniqueness) hold before and after every transaction.
- Isolation
- Concurrent transactions don't see each other's partial work, to a degree set by the isolation level.
- Durability
- Once committed, data survives crashes (it is in the write-ahead log on disk).
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1 AND balance >= 100;
-- the application checks that exactly 1 row changed, otherwise it issues ROLLBACK
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;Isolation levels, MVCC and anomalies such as write skew are covered in ACID, BASE & Isolation Levels.
The NoSQL families
NoSQL systems grew out of web-scale needs in the mid-2000s: Google's Bigtable paper (2006) and Amazon's Dynamo paper (2007) showed how to partition data across thousands of commodity machines and stay available when some of them fail. Each family optimizes for a different shape of data and access.
| Family | Data model | Strengths | Examples | Typical uses |
|---|---|---|---|---|
| Key-value | Opaque value looked up by key | O(1) get/put, trivial to partition, very low latency | Redis, DynamoDB, Riak, etcd | Sessions, carts, caching, feature flags |
| Document | JSON/BSON documents with nested fields and secondary indexes | Flexible schema; a whole aggregate read in one fetch | MongoDB, Couchbase, Firestore | Catalogs, content management, user profiles |
| Wide-column | Rows grouped by partition key, sorted by clustering columns, sparse columns | Massive write throughput, sorted reads within a partition | Cassandra, ScyllaDB, HBase, Bigtable | Messaging, event logs, IoT, time-ordered feeds |
| Graph | Nodes and edges, both with properties | Fast multi-hop traversals | Neo4j, Amazon Neptune, JanusGraph | Social graphs, fraud rings, recommendations |
| Time-series | Timestamped measurements with tags | Compression, retention policies, windowed aggregation | Prometheus, InfluxDB, TimescaleDB | Metrics, monitoring, sensor data |
| Search engine | Documents in an inverted index | Full-text relevance, fuzzy matching, facets | Elasticsearch, OpenSearch, Solr | Search boxes, log analytics. See Search Systems |
Key-value
The simplest model: a giant distributed hash map. The database knows nothing about the value, so it can only fetch by key, but it can do that at almost any scale with predictable single-digit-millisecond (or sub-millisecond) latency.
SET session:9f2c '{"userId":42,"cart":[17,99]}' EX 1800 # expires in 30 min
GET session:9f2c
DEL session:9f2cDocument
A document stores an entire aggregate (an order with its line items and shipping address) together, so the common read is one fetch with no joins. Documents in the same collection may have different fields, and you can still index nested fields.
{
"_id": "order_1042",
"userId": 42,
"status": "paid",
"items": [
{ "sku": "KB-01", "name": "Keyboard", "qty": 1, "priceCents": 8900 },
{ "sku": "MS-07", "name": "Mouse", "qty": 2, "priceCents": 2500 }
],
"shipping": { "city": "Lisbon", "country": "PT" },
"createdAt": "2026-10-02T14:31:00Z"
}db.orders.createIndex({ userId: 1, createdAt: -1 });
db.orders
.find({ userId: 42, status: "paid" })
.sort({ createdAt: -1 })
.limit(20);Wide-column
Wide-column stores such as Cassandra group rows by a partition key (which decides the node) and sort them within the partition by clustering columns. You design one table per query ("query-first modeling"), duplicating data freely, because cross-partition queries and joins are unavailable or expensive.
CREATE TABLE messages_by_conversation (
conversation_id UUID,
sent_at TIMEUUID,
sender_id BIGINT,
body TEXT,
PRIMARY KEY ((conversation_id), sent_at)
) WITH CLUSTERING ORDER BY (sent_at DESC);
-- Fast: one partition on one set of replicas, already sorted newest-first
SELECT sender_id, body, sent_at
FROM messages_by_conversation
WHERE conversation_id = 9b2f6c1e-3d4a-4c7e-9a10-2b8d5e6f7a81
LIMIT 50;Graph
When the question is about relationships several hops deep (friends of friends, accounts sharing devices with a known fraudster), a graph database follows edges directly instead of performing one self-join per hop.
MATCH (me:Person {name: 'Ana'})-[:FOLLOWS]->(friend)-[:FOLLOWS]->(fof)
WHERE fof <> me AND NOT (me)-[:FOLLOWS]->(fof)
RETURN fof.name, count(friend) AS mutual
ORDER BY mutual DESC
LIMIT 10;SQL vs NoSQL at a glance
| Dimension | Relational (SQL) | NoSQL (typical) |
|---|---|---|
| Data model | Tables of rows with fixed columns | Key-value pairs, documents, wide rows or graphs |
| Schema | Schema-on-write: enforced by the database; changed with migrations | Schema-on-read: flexible; enforced (or not) by application code |
| Queries | SQL with ad hoc joins, aggregations and subqueries | Per-store APIs; limited or no joins; model data around known queries |
| Relationships | Foreign keys and joins | Embedding and duplication, or joins in the application (graph DBs excel here) |
| Transactions | Multi-row, multi-table ACID | Often single-item or single-partition atomicity; some offer multi-item transactions (MongoDB, DynamoDB) |
| Consistency | Strong on a single primary | Often eventual or tunable (Cassandra, DynamoDB's default reads); some strong (MongoDB primary reads, HBase) |
| Scaling | Vertical first, then read replicas; sharding is manual (Vitess, Citus) | Horizontal partitioning built in from day one |
| Sweet spot | Complex queries and invariants at moderate scale | Simple, predictable access patterns at very large scale |
| Maturity | 40+ years of tooling, optimizers and expertise | Varies widely by product |
| Examples | PostgreSQL, MySQL, SQL Server, Oracle, SQLite | DynamoDB, MongoDB, Cassandra, Redis, Neo4j |
Schema flexibility is not "schemaless"
Your application still expects certain fields, so the schema hasn't disappeared: it has moved from the database into code, where nothing enforces it. Teams handle evolution with a schemaVersion field and lazy migration on read. Meanwhile relational databases have added flexibility of their own: PostgreSQL's JSONB columns can be indexed and queried, giving document-style storage next to relational tables.
Scaling
A single modern relational server with fast SSDs and plenty of RAM handles tens of thousands of transactions per second and multiple terabytes, which covers most products for a long time, especially with read replicas (Database Replication). Distributed NoSQL stores partition data by key from the start (Sharding & Partitioning), so adding nodes adds capacity linearly, as long as every query includes the partition key. Queries that don't must scatter to every node.
Consistency
ACID
- Transactions are all-or-nothing and isolated
- Reads see the latest committed data (on the primary)
- Easy to reason about; invariants are protected by the database
BASE
- Basically Available, Soft state, Eventually consistent
- Replicas converge over time; reads may be stale
- Stays available during partitions. See CAP Theorem & PACELC and Quorums & Leaderless Replication
How to choose
- 1
List your access patterns
Which queries, how often, with what latency target, and what read/write ratio? Data models follow from queries.
- 2
Default to relational
If the data is relational, needs multi-row transactions or ad hoc queries, and fits on one primary plus replicas, start with PostgreSQL or MySQL.
- 3
Key-value or wide-column for scale
Simple lookups by key at very high volume, huge append-heavy write rates, or multi-region availability point to DynamoDB, Cassandra or ScyllaDB.
- 4
Document for aggregates
If you read and write whole aggregates with varied attributes, a document store (or Postgres JSONB) fits naturally.
- 5
Graph for deep relationships
If multi-hop traversals are the core query, use a graph database.
- 6
Add specialists, not replacements
Search, metrics and analytics get their own engines (Elasticsearch, Prometheus, ClickHouse or BigQuery), fed from the primary store.
| If you need... | Reach for |
|---|---|
| Money, inventory, bookings: invariants across rows | PostgreSQL or MySQL. See Design a Payment System and Design a Ticket Booking System |
| Millions of append-only writes per second | Cassandra, ScyllaDB, Bigtable |
| Single-digit-millisecond key lookups at any scale, fully managed | DynamoDB |
| A product catalog with varied attributes per category | MongoDB, or PostgreSQL with JSONB |
| Friends-of-friends and fraud-ring traversals | Neo4j or Neptune |
| Full-text search with typo tolerance and facets | Elasticsearch or OpenSearch |
| Metrics and monitoring data | Prometheus, InfluxDB, TimescaleDB |
| SQL and strong consistency across regions | Spanner, CockroachDB (NewSQL) |
Polyglot persistence
Large systems rarely pick one database. They use the best store for each job and keep them in sync with events, not with fragile dual writes from application code. Press play to watch an e-commerce order and search flow through several stores.
NewSQL: SQL at NoSQL scale
Distributed SQL (NewSQL) databases split tables into ranges, replicate each range with a consensus protocol (Consensus: Raft & Paxos) and keep full SQL with ACID transactions across nodes and even regions. Google Spanner uses TrueTime (GPS and atomic clocks) to give globally consistent transactions; CockroachDB speaks the PostgreSQL wire protocol and replicates each range with Raft; TiDB is MySQL-compatible; YugabyteDB offers Postgres-compatible SQL on a distributed storage layer.
What you gain
- Horizontal scaling without manual sharding
- Strong consistency and SQL transactions
- Survives node, zone or region failures automatically
What you pay
- Higher write latency: commits need a majority of replicas, possibly in other regions
- More complex to operate, or a premium for managed services
- Some features and extensions of single-node Postgres/MySQL are missing
Key takeaways
- Relational databases offer a fixed schema, joins, ad hoc SQL and multi-row ACID transactions; they scale further than most people assume.
- NoSQL is several families: key-value, document, wide-column, graph, plus time-series and search engines, each built for a specific access pattern.
- NoSQL usually trades joins, ad hoc queries and multi-item transactions for built-in partitioning, flexible schemas and high availability.
- Model NoSQL data around known queries (query-first) and always include the partition key in hot queries.
- Polyglot persistence uses the right store per job, synchronized with CDC or outbox events rather than dual writes.
- NewSQL (Spanner, CockroachDB) offers SQL and strong consistency at scale, paying in write latency and complexity.
Common pitfalls
- Choosing NoSQL "for scale" when the data fits comfortably on one relational primary with replicas.
- Modeling a wide-column or key-value store like a relational database and then needing joins or scatter-gather queries everywhere.
- Believing "schemaless" means no schema work: the schema just moves into application code, unenforced.
- Dual-writing to several databases from the application and ending up with silent inconsistencies.
- Using eventual consistency for data with strict invariants such as balances or seat inventory.
Interview tips
- Start from access patterns and consistency requirements, then pick the model; say what you give up.
- It's fine (and common) to use more than one store; explain how they stay in sync.
- For each NoSQL choice, state the partition key and the main query it serves.
Real-world applications
- PostgreSQL/MySQL for orders, payments, users and anything transactional.
- DynamoDB or Redis for sessions, carts and high-scale key lookups.
- Cassandra/ScyllaDB for messaging, activity feeds and IoT telemetry.
- MongoDB for catalogs and content with varied structure.
- Neo4j for social graphs and fraud detection; Elasticsearch for search.
Test yourself
Which database family is best suited to "find friends of friends who aren't already my friends"?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.