Module 03 // DataLesson 09 / 3420 min read
SQL vs NoSQL
SQL databases store data in tables with strict structure and powerful queries; NoSQL databases trade some of that for flexible shapes and easier scaling. The right choice depends on how you'll read and write the data.
Think of it like this
Analogy
A SQL database is a well-run filing cabinet with labeled folders and forms. Every form has the same boxes, cross-references between folders are checked, and you can ask complicated questions like “every customer in Madrid who ordered twice last month”.
A NoSQL database is more like a set of specialist containers: a key cabinet where you fetch anything instantly by its tag, a box of notebooks where each page can be laid out differently, a huge ledger that's easy to split across many rooms, or a corkboard of pins and strings showing who's connected to whom.
The problem it solves
The database is usually the hardest part of a system to change later. Pick a store that fights your access patterns and you'll pay for it constantly: slow queries, painful migrations, or a system that can't grow past one machine. Pick one that gives up guarantees you needed, like transactions, and you'll get subtle data bugs.
A real example
Example
An online bookstore picks its databases
Orders and payments go in PostgreSQL. Placing an order takes money from a gift card, reduces stock and creates the order, and all of it must happen together or not at all. That's what transactions are for.
The shopping cart lives in a key-value store. It's read and written constantly, always by cart ID, and losing one occasionally isn't a disaster.
The catalog is a document store, because a book has an author and ISBN while a gift voucher has neither. Search runs on a search engine built for text. One shop ends up with four kinds of database, each chosen for how its data is actually used.
How it works
Relational (SQL) databases
Data lives in tables with a fixed schema. Relationships are expressed with keys, and SQL lets you join tables and filter however you like.
SELECT u.name, COUNT(o.id) AS orders
FROM users u JOIN orders o ON o.user_id = u.id
WHERE o.created_at > now() - interval '30 days'
GROUP BY u.name;Relational databases offer ACID transactions: a group of changes either all happen or none do, and concurrent transactions don't see each other's half-finished work. Examples: PostgreSQL, MySQL, SQL Server.
They scale up well and handle a lot of traffic with good indexes and read replicas. Spreading writes across many machines (sharding) is possible but takes work, though newer distributed SQL databases like Spanner and CockroachDB do it for you.
NoSQL databases
NoSQL means “not only SQL”. It covers four main types:
| Type | Data model | Great at | Examples |
|---|---|---|---|
| Key-value | key → value | Lookups by exact key at huge scale: sessions, carts, caches | DynamoDB, Redis |
| Document | key → JSON document | Objects read as a whole, with changing shapes | MongoDB, Firestore, Cosmos DB |
| Wide-column | partition key → sorted rows | Massive write volumes, time series, event logs | Cassandra, Bigtable |
| Graph | nodes and edges | Walking relationships: social graphs, fraud, recommendations | Neo4j, Neptune |
Most NoSQL databases are designed to partition data across many machines from the start. The price is usually fewer query options: you design tables around the questions you'll ask, often duplicating data so each common read is a single lookup.
Design around access patterns
With SQL you design the data model first and write queries later. With most NoSQL stores you list your queries first, then design keys to answer each one quickly.
For a key-value or wide-column store holding chat messages, you might use:
- Partition key:
conversation_id. All messages in a chat live together. - Sort key:
sent_at. Messages are already in time order.
“Last 50 messages in this chat” becomes one efficient read. “All messages containing the word pizza” isn't supported at all; you'd add a search index for that.
How to choose
- Default to a relational database for most products. It's flexible, safe, and handles far more scale than most apps reach.
- Pick key-value or document when access is mostly by ID, the shape varies, or you need huge, predictable scale with little operational work.
- Pick wide-column for very high write throughput with simple access by key and time.
- Pick a graph database when the questions are about multi-step relationships.
- Mix them. Real systems often use a relational database as the source of truth, a key-value cache, a search index and a data warehouse together.
Trade-offs
What you gain
- SQL: transactions, strong consistency, flexible queries and joins, mature tools.
- NoSQL: scales out easily, flexible schemas, very fast key lookups, built-in replication.
What it costs you
- SQL: scaling writes past one machine is hard; schema changes on huge tables need care.
- NoSQL: limited queries and joins, data is often duplicated, transactions are narrower or more expensive, and schema discipline moves into your code.
When not to use it
- Avoid NoSQL just to “be web scale” when the data is relational and fits on one machine.
- Avoid forcing a relational database to be a high-volume event log or a graph walker when a specialized store does it far better.
In the cloud
Relational (SQL) databasesEvery major cloud sells this as a managed service, so you configure it rather than build it.
AWS2
- Amazon RDS (opens vendor docs)
Managed PostgreSQL, MySQL, MariaDB, SQL Server, Oracle and Db2.
- Amazon Aurora (opens vendor docs)
AWS's MySQL- and PostgreSQL-compatible database with storage replicated across three zones.
Azure2
- Azure SQL Database (opens vendor docs)
Managed SQL Server database engine.
- Azure Database for PostgreSQL (opens vendor docs)
Managed PostgreSQL (flexible server).
Google Cloud2
- Cloud SQL (opens vendor docs)
Managed PostgreSQL, MySQL and SQL Server.
- AlloyDB for PostgreSQL (opens vendor docs)
Google's PostgreSQL-compatible database tuned for heavy transactional and analytical work.
One writable primary with a standby in another zone for failover, plus read replicas.
- App servers
- RDS primary (Multi-AZ)
- Read replicas
NoSQL databasesEvery major cloud sells this as a managed service, so you configure it rather than build it.
AWS3
- Amazon DynamoDB (opens vendor docs)
Serverless key-value and document database with single-digit-millisecond reads at any scale.
- Amazon DocumentDB (opens vendor docs)
MongoDB-compatible document database.
- Amazon Neptune (opens vendor docs)
Graph database for highly connected data like social graphs and fraud rings.
Azure1
- Azure Cosmos DB (opens vendor docs)
Globally distributed NoSQL database with document, key-value, graph and column-family APIs.
Google Cloud2
- Firestore (opens vendor docs)
Serverless document database with real-time sync for apps.
- Bigtable (opens vendor docs)
Wide-column database for huge, fast-growing datasets like time series and events.
Interview questions
Try answering out loud first, then open the model answer.
SQL or NoSQL for a new social app? Justify it.
Model answer
I'd start with a relational database for users, posts, follows and likes. The data is relational, I need constraints and transactions (for example creating a post and incrementing a counter), and PostgreSQL with indexes, read replicas and caching goes a very long way. I'd add specialized stores where access patterns demand it: a key-value store or cache for timelines and counters, a search index for text search, and maybe a wide-column store for the activity feed once write volume gets very large.
What is denormalization and why do NoSQL designs use it?
Model answer
Denormalization means storing the same data in more than one place so that a read needs one lookup instead of a join. For example, storing the author's name inside each post. NoSQL stores usually can't join across partitions efficiently, so you shape data around your reads. The cost is that updates must change every copy, and copies can briefly disagree.
What does ACID stand for and why does it matter?
Model answer
Atomicity: all of a transaction happens or none of it does. Consistency: the database moves from one valid state to another, respecting constraints. Isolation: concurrent transactions don't see each other's partial results. Durability: once committed, data survives crashes. It matters for anything where partial updates would be wrong: money transfers, inventory, bookings.
Quiz
Pick an answer to see whether it’s right and why.
0 of 7 answered
Key terms
- SQL
- The language for querying relational databases, which store data in tables with fixed columns.
- NoSQL
- Databases that don't use relational tables, such as key-value, document, wide-column and graph stores.
- ACID
- Atomic, Consistent, Isolated, Durable. The guarantees that make database transactions all-or-nothing and safe.
- Schema
- The defined shape of your data, such as table columns and their types.
- Key-value store
- A database that stores values under unique keys, like a giant dictionary. Very fast lookups by key.
- Document database
- A database that stores JSON-like documents, each of which can have its own nested structure.
- Wide-column store
- A database that groups data by a partition key and sorts rows inside each partition; built for huge write volumes.
- Graph database
- A database that stores things and the connections between them, made for questions like "friends of friends".
- Database
- Software that stores data on disk in an organized way so it can be queried and survives restarts.
Progress is saved in this browser only.