Skip to main content
1:1 mock interviews with Sumit, scored on a real hiring rubric.Book a slot →

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.

Sumit KumarUpdated Oct 11, 20264 min readSystem Design
SQL vs NoSQL Databases: Differences, Types and When to Use Each

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 vs NoSQL databases: relational tables with fixed schema and joins compared with document, key-value, wide-column and graph NoSQL data models

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.

SQL
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.

JavaScript
// 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 modelTables with rows and columnsDocuments, key-value, wide-column or graph
SchemaFixed, enforced by the databaseFlexible, often enforced by the application
RelationshipsJoins and foreign keysEmbedding or denormalisation; few or no joins
TransactionsStrong multi-row ACIDVaries; often single-document or tunable
ConsistencyStrong by defaultOften eventual or tunable
ScalingMostly vertical; sharding is harderBuilt for horizontal scaling
Query languageStandard SQLDatabase-specific APIs
Best forComplex queries, financial data, reportingHigh scale, flexible or fast-changing data

The four types of NoSQL database#

TypeData modelExamplesGreat for
DocumentJSON/BSON documentsMongoDB, Couchbase, FirestoreProduct catalogues, content, user profiles
Key-valueKey → opaque valueRedis, DynamoDB, MemcachedCaching, sessions, counters, leaderboards
Wide-columnRows with dynamic column familiesCassandra, HBase, ScyllaDBTime series, IoT, write-heavy workloads
GraphNodes and edgesNeo4j, Amazon NeptuneSocial networks, recommendations, fraud detection

Key-value example (Redis)#

Bash
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 10

Wide-column example (Cassandra)#

SQL
-- 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)#

Text
// 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.

The lines are blurring

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#

SQLNoSQL
Model the entities, normalise, then write any query you needModel the queries first, then shape data to serve them
Avoid duplicationDuplicate data to avoid joins
Ad-hoc questions are easyNew access patterns may need new tables or indexes
Unbounded arrays

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.