Hero image for SQL vs NoSQL: When to Use Which & Multi-Document ACID

SQL vs NoSQL: When to Use Which & Multi-Document ACID

nosql mongodb sql-server database architecture decision-guide

Prerequisites: Understanding of both SQL and NoSQL concepts. See DB 01 Networking Fundamentals and NOSQL 01 Introduction.

This is the ultimate decision guide for choosing between relational (SQL) and non-relational (NoSQL) databases.


Part A: Fundamental Differences

1. The Core Difference

NoSQL (Non-Relational)

SQL (Relational)

Tables

Rows

Strict Schema

ACID

Collections

Documents

Flexible Schema

BASE

2. Feature Comparison

FeatureSQL (e.g., SQL Server)NoSQL (e.g., MongoDB)
Data ModelTables with fixed columnsJSON documents (flexible)
SchemaRigid, predefinedDynamic, schema-less
RelationshipsJOINs across tablesEmbedded documents or $lookup
ScalingVertical (bigger server)Horizontal (more servers)
TransactionsMulti-table ACIDPer-document (multi-doc available)
Query LanguageSQL (standardized)Varies by database
Best ForComplex queries, consistencyScale, flexibility, speed

[!CAUTION] Common Myths Debunked:

  • ❌ “NoSQL doesn’t support ACID” → MongoDB 4.0+ has multi-document transactions
  • ❌ “SQL can’t scale horizontally” → SQL Server supports Read Replicas, and sharding (though more complex)
  • ❌ “NoSQL is always faster” → Depends on query patterns and index design; poorly indexed MongoDB can be slower than well-tuned SQL
  • ❌ “Schema-less means no planning” → You still need to design for your query patterns

3. Architecture Comparison

MongoDB Architecture

Application

mongos Router

Shard 1

Shard 2

Shard 3

SQL Server Architecture

Application

Single Database Server

Local Storage


Part B: Decision Framework

4. The Decision Tree

Yes, stable

No, evolving

Yes, many

No, few

Massive scale

Moderate

Absolutely

Eventual OK

New Project

Data structure

well-defined?

Need complex

JOINs?

Consider NoSQL

Choose SQL

Scale requirements?

ACID critical?

5. Quick Decision Matrix

RequirementChoose SQLChoose NoSQL
Complex relationships⚠️
Strict consistency⚠️
Ad-hoc queries⚠️
Flexible schema⚠️
Horizontal scaling⚠️
High write throughput⚠️
Rapid development⚠️
Geographic distribution⚠️

[!TIP] Team Factor: Technology decisions aren’t just technical. If your team has 10 years of SQL expertise and zero MongoDB experience, switching databases means:

  • 📚 Steep learning curve
  • 🐛 More bugs during transition
  • 💰 Training costs

Tech debt includes knowledge debt. Factor in team skills when choosing databases.

6. Use Case Guide

Choose SQL When:

ScenarioWhy SQL
Banking/FinanceACID transactions, audit requirements
ERP SystemsComplex relationships between entities
Inventory ManagementExact stock counts, no overselling
Reporting/AnalyticsComplex JOINs, aggregations
Legacy IntegrationStandard SQL interface

Choose NoSQL When:

ScenarioWhy NoSQL
Real-time AppsLow latency, high concurrency
Content ManagementVariable content structure
IoT/Sensor DataTime-series, high write volume
Mobile AppsOffline sync, flexible schema
GamingLeaderboards, user profiles
Product CatalogsVariable attributes per product

Part C: Multi-Document ACID Transactions

7. The MongoDB ACID Evolution

Early MongoDB was criticized for lacking transactions. Since version 4.0 (2018), MongoDB supports multi-document ACID transactions.

2009MongoDB Released(no transactions)2018Version 4.0(Multi-doctransactions)2019Version 4.2(Shardedtransactions)2021Version 5.0(Improvedperformance)MongoDB Transaction Support

8. When to Use Transactions

ScenarioUse Transaction?
Update single document❌ Already atomic
Update embedded array❌ Already atomic
Transfer money between accounts✅ Yes
Create order + reduce inventory✅ Yes
Multi-collection updates✅ Yes

9. Transaction Syntax

// Start a session
const session = client.startSession();

try {
  session.startTransaction();
  
  // Operation 1: Debit from account A
  await db.accounts.updateOne(
    { _id: "accountA" },
    { $inc: { balance: -100 } },
    { session }
  );
  
  // Operation 2: Credit to account B
  await db.accounts.updateOne(
    { _id: "accountB" },
    { $inc: { balance: 100 } },
    { session }
  );
  
  // Commit the transaction
  await session.commitTransaction();
  console.log("Transfer successful");
  
} catch (error) {
  // Abort on any error
  await session.abortTransaction();
  console.log("Transfer failed, rolled back");
  
} finally {
  session.endSession();
}

10. Transaction Best Practices

PracticeReason
Keep transactions shortLocks held during transaction
Limit operationsPerformance impact
Use retry logicTransient errors possible
Prefer schema design over transactionsEmbedding avoids multi-doc updates

[!WARNING] Transaction Performance Cost: Multi-document transactions use Snapshot Isolation and create locks on involved documents. Long transactions increase lock contention and memory usage. This is why schema embedding (denormalization) should always be your first choice — use transactions only as a last resort when cross-document atomicity is absolutely required.

// With retry logic
async function runTransactionWithRetry(session, txnFunc) {
  while (true) {
    try {
      await txnFunc(session);
      break;
    } catch (error) {
      if (error.hasErrorLabel("TransientTransactionError")) {
        console.log("Transient error, retrying...");
        continue;
      }
      throw error;
    }
  }
}

Part D: Hybrid Approaches

11. Polyglot Persistence

Use multiple databases for different parts of your system:

E-Commerce Application

SQL Server

Orders, Payments

MongoDB

Product Catalog

Redis

Session Cache

Elasticsearch

Product Search

ComponentDatabaseReason
Orders/PaymentsSQL ServerACID, complex queries
Product CatalogMongoDBFlexible attributes
User SessionsRedisFast, ephemeral
Product SearchElasticsearchFull-text, faceted

[!IMPORTANT] Data Sync Challenge: With polyglot persistence, the same data may exist in multiple databases (e.g., user ID in SQL and MongoDB). Keeping them in sync is critical. Common solutions include:

  • Message Queues (Kafka, RabbitMQ) — Event-driven sync
  • Change Streams (MongoDB) / CDC (SQL Server) — Database-level change capture
  • Eventual Consistency — Accept slight delays between systems

Without proper sync, you risk data inconsistency across your architecture.

12. Migration Strategies

SQL to NoSQL

Phase 3

Phase 2

Phase 1

Keep SQL as primary

Add MongoDB for new features

Dual-write to both

Migrate read traffic

MongoDB as primary

Deprecate SQL

Common Migration Patterns

PatternApproach
Strangler FigGradually replace endpoints
Event SourcingSync via event stream
Dual WriteWrite to both during transition
CDCChange Data Capture for sync

Part E: Real-World Examples

13. E-Commerce Platform

ComponentSQLNoSQL
User accounts✅ Relationships, auth
Shopping cart✅ Fast, session-based
Product catalog✅ Variable attributes
Orders✅ ACID, inventory
Reviews✅ High volume, denormalized
Analytics✅ Complex aggregations

14. Social Media Platform

ComponentSQLNoSQL
User profiles✅ Flexible fields
Friend graph✅ Graph DB (Neo4j)
Posts/Feed✅ High write, timeline
Messages✅ Real-time, partitioned
Ads targeting✅ Complex queries
Billing✅ ACID

15. IoT Platform

ComponentSQLNoSQL
Device registry✅ Relationships
Sensor readings✅ Time-series (Cassandra)
Alerts✅ Fast writes
Configuration✅ Consistency
Analytics✅ Column store

Summary

The Golden Rules

  1. It’s not either/or — use both when appropriate
  2. Start with requirements — not technology preference
  3. Consider future scale — but don’t over-engineer
  4. Schema flexibility — comes with trade-offs
  5. Transactions — MongoDB has them when needed

[!NOTE] Total Cost of Ownership (TCO): Technology choice is also a business decision:

  • SQL Server: High licensing costs, but mature DBA talent pool is widely available
  • MongoDB Atlas: Convenient managed service, but misconfigured sharding can cause cloud bills to skyrocket
  • Open Source (PostgreSQL, MySQL): No license fees, but requires in-house expertise for operations

Always factor in licensing, hosting, and team expertise when making database decisions.

Decision Cheat Sheet

QuestionSQL if…NoSQL if…
SchemaWell-definedEvolving
RelationshipsMany, complexFew, embedded
ConsistencyCriticalEventual OK
Write volumeModerateVery high
ScaleVertical OKNeed horizontal
DevelopmentPlanned, stableAgile, rapid

Final Comparison

AspectSQL ServerMongoDB
Mature tech30+ years15+ years
ToolingExcellentGood
Talent poolLargeGrowing
Cloud supportAzure SQL, RDSAtlas, DocumentDB
Learning curveSQL standardMongoDB-specific
CostLicense + scaleScale-based

💡 Practice Questions

Conceptual

  1. List 3 scenarios where SQL is better than NoSQL and 3 where NoSQL is better.

  2. Explain what polyglot persistence means and give an example architecture.

  3. When did MongoDB add multi-document ACID transactions? When should you use them?

Scenario

  1. Architecture Decision: You’re building an e-commerce platform with: user accounts, product catalog (varying attributes), shopping cart, orders, and product reviews. Which database(s) would you use for each component and why?

  2. Migration: Your company has a legacy SQL Server database with 100 tables. The CEO wants to “move to the cloud and use MongoDB because it’s faster.” How would you respond and what questions would you ask?

💡 View Answer (Scenario 2)

Response Framework:

  1. Clarify the “Why”: What specific problem are we solving? Is it performance, cost, or scalability?
  2. Challenge assumptions: “Faster” depends on workload. MongoDB isn’t inherently faster for all use cases.
  3. Assess the current state:
    • How many tables have complex JOINs?
    • What’s the current pain point (slow queries, scaling issues)?
    • Are there ACID-critical transactions?
  4. Consider alternatives:
    • Can we optimize current SQL (indexes, query tuning)?
    • Azure SQL (cloud) keeps SQL benefits without migration risk
  5. If migration is needed:
    • Use Strangler Fig pattern (gradual replacement)
    • Start with non-critical, schema-flexible components
    • Keep ACID-critical data (payments, inventory) in SQL

Key insight: Migration should be driven by specific requirements, not technology trends.


Looking to deepen your database knowledge? Check out:

  • DB Series — SQL Server from fundamentals to troubleshooting
  • DATA Series — Data engineering and analytics