SQL vs. NoSQL

Difficulty: Intermediate

Question

When should you choose a NoSQL database over a relational SQL database? Walk through how you would decide for a real application.

Answer

Choose a relational (SQL) database by default when your data has clear relationships, you need multi-row transactions, and your queries are varied or not fully known in advance. Choose NoSQL when you have a small number of well-understood access patterns at very high scale, need easy horizontal partitioning, or your data is naturally shaped as documents, key-value pairs, wide rows or graphs. The decision is about access patterns, consistency needs and scale, not about "structured vs unstructured".

The main NoSQL families

TypeModelGood forExamples
Key-valueOpaque value by keySessions, caches, rate limitsRedis, DynamoDB
DocumentJSON-like nested docsCatalogues, user profiles, CMSMongoDB, Couchbase
Wide-columnRows partitioned by key, sorted columnsTime series, messaging, high write volumeCassandra, ScyllaDB, Bigtable
GraphNodes and edgesSocial graphs, fraud rings, recommendationsNeo4j, Neptune

Where SQL wins

  • Integrity: foreign keys, unique and check constraints, and ACID transactions across tables. Ledgers, orders, payments and inventory belong here.
  • Ad hoc queries: joins, aggregations and new reporting questions do not require reshaping data.
  • Mature tooling: migrations, ORMs, query planners, point-in-time recovery.
  • Scale is higher than people assume: a single well-indexed PostgreSQL or MySQL instance with read replicas handles a very large share of real workloads, and distributed SQL (CockroachDB, YugabyteDB, Spanner, TiDB) scales horizontally while keeping SQL.

Where NoSQL wins

  • Predictable, massive throughput on known keys: DynamoDB or Cassandra give consistent single-digit millisecond latency at very high request rates when queries always include the partition key.
  • Write-heavy, append-mostly data: chat messages, IoT readings, activity logs.
  • Flexible, nested data: a product catalogue where a phone and a saree have completely different attributes fits documents naturally (though Postgres jsonb also handles this well).
  • Built-in multi-region replication with tunable consistency.

The trade-offs people miss

  • NoSQL modelling is query-first: in DynamoDB or Cassandra you design tables around exact queries. Adding a new query later can mean a new table or index and a backfill.
  • Joins move into application code, and denormalized copies must be kept in sync.
  • Many NoSQL stores now support transactions (MongoDB 4.0+, DynamoDB TransactWriteItems), and Postgres supports JSON documents, so the line has blurred.

A practical decision process

  1. List the top queries and writes, with expected volume.
  2. Ask whether you need cross-entity transactions or strong constraints. If yes, lean SQL.
  3. Ask whether a single primary plus replicas can handle the write load for a few years. If yes, lean SQL.
  4. Use NoSQL for the specific component that needs it. Most large systems are polyglot: a Zomato-style app might keep orders and payments in MySQL or Postgres, sessions and rate limits in Redis, search in Elasticsearch, and event history in Cassandra or a data lake.
Choosing a database for a new service. Start from access patterns and integrity needs, not from hype.
  1. List top reads and writes with volume: Know your queries before choosing a model.
  2. Need multi-row transactions or constraints?: Payments, orders and inventory point to SQL.
  3. Can one primary handle writes?: If yes, SQL with replicas is simplest.
  4. Few known key-based queries at huge scale?: Key-value or wide-column fits well.
  5. Pick per component: Mix SQL, cache, search and NoSQL as needed.

Code examples

Same order modelled relationally and as a document

// Relational: normalized tables joined at query time
// orders(id, user_id, status) + order_items(order_id, sku, qty, price_paise)

// Document (MongoDB): one read returns the whole order
db.orders.insertOne({
  _id: "ord_1001",
  userId: "u_42",
  status: "PLACED",
  items: [
    { sku: "TSHIRT-M", qty: 2, pricePaise: 49900 },
    { sku: "MUG-01",  qty: 1, pricePaise: 29900 }
  ],
  address: { city: "Bengaluru", pincode: "560001" }
});

// Fast for "get order by id", awkward for
// "total units sold per SKU across all orders" without aggregation pipelines
db.orders.aggregate([
  { $unwind: "$items" },
  { $group: { _id: "$items.sku", units: { $sum: "$items.qty" } } }
]);

Embedding makes the main access pattern a single read, but cross-document analytics and keeping duplicated data in sync become your responsibility.

Key points

  • Default to SQL for relational data, transactions and evolving queries.
  • NoSQL shines for a few known access patterns at very high scale or write volume.
  • NoSQL schema design is query-first; new queries can need new tables or indexes.
  • The boundary has blurred: Postgres has jsonb, MongoDB and DynamoDB have transactions.
  • Real systems are usually polyglot.

Common follow-up questions

  • How would you model a one-to-many relationship in DynamoDB?
  • What is distributed SQL and when would you choose it?
  • How do you handle joins in a document database?
  • Would you store a UPI transaction ledger in MongoDB? Why or why not?

Interview tips

  • Avoid "NoSQL is for unstructured data, SQL for structured"; talk about access patterns and consistency.
  • Name specific databases for specific components instead of one database for everything.
  • Acknowledge that relational databases scale further than many candidates claim.

Concepts covered

Relational Model, Document Store, Key-Value Store, Wide-Column, Horizontal Scaling, Access Patterns

More Database Design questions