SQL vs NoSQL Databases: Differences, Types and When to Use Each
A clear comparison of SQL (relational) and NoSQL databases: data models, schemas, scaling, consistency, the four NoSQL types with examples, query code side by side and a decision guide.
Choosing a database is one of the longest-lasting decisions in a project. SQL databases store data in related tables with a fixed schema; NoSQL databases trade some of that structure for flexible data models and easier horizontal scaling. Neither is "better": each fits different access patterns.
Two ways to model data#
SQL: tables, rows and joins#
Relational databases (PostgreSQL, MySQL, SQL Server, Oracle) normalise data into tables linked by foreign keys, and use SQL to query across them.
CREATE TABLE users (
id BIGSERIAL PRIMARY KEY,
name TEXT NOT NULL,
email TEXT UNIQUE NOT NULL
);
CREATE TABLE orders (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT REFERENCES users(id),
total NUMERIC(10,2) NOT NULL,
created_at TIMESTAMPTZ DEFAULT now()
);
-- Total spent per user in the last 30 days
SELECT u.name, SUM(o.total) AS spent
FROM users u
JOIN orders o ON o.user_id = u.id
WHERE o.created_at > now() - INTERVAL '30 days'
GROUP BY u.name
ORDER BY spent DESC;NoSQL: documents shaped like your objects#
A document database such as MongoDB stores JSON-like documents. Related data that is read together is often embedded in one document.
// One user document with embedded recent orders
{
_id: ObjectId("..."),
name: "Asha",
email: "asha@example.com",
recentOrders: [
{ orderId: 9012, total: 1499, createdAt: ISODate("2026-10-01") },
{ orderId: 9077, total: 349, createdAt: ISODate("2026-10-07") }
]
}
// Query
db.users.find(
{ "recentOrders.total": { $gt: 1000 } },
{ name: 1, email: 1 }
);Key differences#
| SQL (relational) | NoSQL | |
|---|---|---|
| Data model | Tables with rows and columns | Documents, key-value, wide-column or graph |
| Schema | Fixed, enforced by the database | Flexible, often enforced by the application |
| Relationships | Joins and foreign keys | Embedding or denormalisation; few or no joins |
| Transactions | Strong multi-row ACID | Varies; often single-document or tunable |
| Consistency | Strong by default | Often eventual or tunable |
| Scaling | Mostly vertical; sharding is harder | Built for horizontal scaling |
| Query language | Standard SQL | Database-specific APIs |
| Best for | Complex queries, financial data, reporting | High scale, flexible or fast-changing data |
The four types of NoSQL database#
| Type | Data model | Examples | Great for |
|---|---|---|---|
| Document | JSON/BSON documents | MongoDB, Couchbase, Firestore | Product catalogues, content, user profiles |
| Key-value | Key → opaque value | Redis, DynamoDB, Memcached | Caching, sessions, counters, leaderboards |
| Wide-column | Rows with dynamic column families | Cassandra, HBase, ScyllaDB | Time series, IoT, write-heavy workloads |
| Graph | Nodes and edges | Neo4j, Amazon Neptune | Social networks, recommendations, fraud detection |
Key-value example (Redis)#
SET session:8f2c '{"userId":42,"role":"admin"}' EX 3600 # expires in 1 hour
GET session:8f2c
INCR page:home:views
ZADD leaderboard 1520 "asha" 1375 "ravi"
ZREVRANGE leaderboard 0 9 WITHSCORES # top 10Wide-column example (Cassandra)#
-- Design the table around the query: "readings for a sensor on a day"
CREATE TABLE sensor_readings (
sensor_id TEXT,
day DATE,
ts TIMESTAMP,
value DOUBLE,
PRIMARY KEY ((sensor_id, day), ts)
) WITH CLUSTERING ORDER BY (ts DESC);Graph example (Neo4j Cypher)#
// Friends-of-friends that Asha doesn't already follow
MATCH (a:User {name: "Asha"})-[:FOLLOWS]->()-[:FOLLOWS]->(fof)
WHERE NOT (a)-[:FOLLOWS]->(fof) AND a <> fof
RETURN fof.name, count(*) AS mutual
ORDER BY mutual DESC LIMIT 5;Consistency: ACID vs BASE#
Relational databases follow ACID: atomicity, consistency, isolation and durability (see ACID transactions and isolation levels). Many distributed NoSQL systems follow BASE: basically available, soft state, eventually consistent. They favour availability during network partitions, as described by the CAP theorem.
PostgreSQL has powerful JSONB columns; MongoDB supports multi-document ACID transactions; distributed SQL databases such as CockroachDB, YugabyteDB and Google Spanner scale horizontally while keeping SQL and strong consistency.
Data modelling mindset#
| SQL | NoSQL |
|---|---|
| Model the entities, normalise, then write any query you need | Model the queries first, then shape data to serve them |
| Avoid duplication | Duplicate data to avoid joins |
| Ad-hoc questions are easy | New access patterns may need new tables or indexes |
Embedding is great for small, bounded lists. Don't embed something that grows forever, like every order a user has ever placed; MongoDB documents are capped at 16 MB, and huge documents are slow to read and update.
How to choose#
- Pick SQL when data is relational, integrity matters (payments, inventory, bookings), you need complex queries or reports, or you're not sure yet. PostgreSQL is an excellent default.
- Pick a document store when records are self-contained and their shape varies or changes often.
- Pick key-value for caching, sessions and very fast lookups by key.
- Pick wide-column for massive write volumes and time-series data with known queries.
- Pick a graph database when relationships themselves are the main thing you query.
Many real systems use several (polyglot persistence): PostgreSQL for orders, Redis for caching, Elasticsearch for search. In microservices, each service can pick the store that fits.
Key takeaways#
- SQL databases use fixed schemas, joins and strong ACID transactions.
- NoSQL databases offer flexible schemas and easy horizontal scaling, often with eventual consistency.
- The four NoSQL families are document, key-value, wide-column and graph, each suited to different workloads.
- Model SQL around entities and NoSQL around queries.
- Default to a relational database unless a specific scale or data-shape need points to NoSQL; many systems use both.