SQL vs NoSQL: choosing a database

Master the trade-offs between relational and non-relational databases. Learn when to use SQL, Document, Key-Value, or Wide-Column stores in system design interviews.

beginner12 min readBy CureBugs EditorialUpdated 5 Nov 2026

Choosing the right database is arguably the most critical decision in any system design interview. Whether you are designing a massive social network, a high-throughput URL shortener, or a highly transactional payment gateway, your interviewer will inevitably ask: "What database would you use, and why?" Your choice dictates how your system scales, how it handles network partitions, and how quickly developers can iterate. In this comprehensive guide, we will break down the SQL vs NoSQL debate, explore the different flavors of NoSQL, and give you the frameworks you need to ace your next system design round.

What it is and why it matters

At a high level, databases are categorized into two major paradigms: Relational (SQL) and Non-Relational (NoSQL). Understanding the fundamental philosophy behind each is crucial before diving into specific technologies.

The SQL Paradigm (Relational)

Relational databases (like PostgreSQL, MySQL, and Oracle) have been the bedrock of software engineering since the 1970s. They organize data into tables (relations) with strict, predefined schemas. Every row represents a record, and every column represents an attribute. Relationships between different entities are enforced using Foreign Keys, allowing developers to perform complex JOIN operations to stitch data back together.

The defining characteristic of SQL databases is their strict adherence to ACID properties:

  • Atomicity: Transactions are "all or nothing." If a failure occurs halfway through a multi-step database update (e.g., deducting money from Account A and adding it to Account B), the entire transaction is rolled back.
  • Consistency: The database strictly enforces rules, constraints, and triggers. Data always moves from one valid state to another.
  • Isolation: Concurrent transactions do not interfere with each other, preventing race conditions.
  • Durability: Once a transaction is committed, it remains saved even in the event of a power loss or system crash.

Because of these guarantees, SQL is the undisputed champion for financial systems, inventory management, and any domain where data integrity is absolutely paramount.

The NoSQL Paradigm (Non-Relational)

NoSQL (often interpreted as "Not Only SQL") emerged in the late 2000s. As web-scale companies like Google, Amazon, and Facebook experienced exponential growth, they hit the physical limits of vertical scaling (buying bigger, more expensive servers). They needed databases that could scale horizontally across thousands of cheap, commodity servers.

To achieve this massive scale, NoSQL databases drop strict ACID guarantees and complex JOIN capabilities in favor of BASE semantics:

  • Basically Available: The system guarantees availability for reads and writes, even if some nodes in the cluster fail.
  • Soft state: The state of the system may change over time, even without new input, due to background replication.
  • Eventual consistency: Given enough time without new updates, all nodes in the distributed system will converge to the same data.

NoSQL is not a single technology; it is an umbrella term for several different database architectures (Key-Value, Document, Wide-Column, Graph), each optimized for specific access patterns.

How it works: Polyglot Persistence

In modern system design, you rarely rely on a single database to do everything. Instead, microservice architectures use Polyglot Persistence: picking the right database for the specific workload of each microservice.

Here is how a typical e-commerce backend might distribute its data across different database types:

  • User Service (PostgreSQL): Manages user accounts, passwords, and billing information. Requires strict ACID compliance and structured schemas.
  • Cart Service (Redis): Manages temporary shopping carts. Requires ultra-low latency (sub-millisecond) and automatic expiration (TTL), making an in-memory Key-Value store perfect.
  • Product Catalog (MongoDB): Stores product details. Products have vastly different attributes (a laptop has RAM and CPU specs; a t-shirt has size and color). A flexible Document store handles this unstructured data gracefully.
  • Analytics Service (Cassandra): Ingests millions of clickstream events per minute. Requires massive write throughput and horizontal scalability, which a Wide-Column store provides via LSM-trees.

The main strategies compared

To choose the right database in an interview, you must know the sub-types of NoSQL. Here is a comprehensive comparison table:

Database TypeData ModelExamplesBest Used ForAnti-Patterns
Relational (SQL)Tables, Rows, ColumnsPostgreSQL, MySQLFinancial ledgers, ERP systems, strict schemasHigh-velocity unstructured data, massive horizontal scale
Key-Value (NoSQL)Hash map (Key -> Value)Redis, DynamoDB, MemcachedCaching, session management, rate limiting, leaderboardsComplex queries, fetching data by value, relationships
Document (NoSQL)JSON / BSON documentsMongoDB, CouchbaseContent management, user profiles, product catalogsMulti-document ACID transactions, complex graph traversals
Wide-Column (NoSQL)Column familiesCassandra, HBaseTime-series data, IoT sensor data, massive write-heavy logsAd-hoc queries, frequent updates/deletes, complex joins
Graph (NoSQL)Nodes and EdgesNeo4j, Amazon NeptuneSocial networks, fraud detection, recommendation enginesSimple CRUD operations, bulk data scans

Trade-offs and failure modes

When you propose a database in a system design interview, the interviewer will immediately probe you on the trade-offs. Here are the core dimensions you must discuss.

1. Scaling: Vertical vs Horizontal

SQL databases traditionally scale vertically. If your database is slow, you buy a bigger server (more CPU, more RAM, faster SSDs). For example, an AWS RDS instance can scale up to 128 vCPUs and 4TB of RAM, handling around 80,000 IOPS. For 95% of companies, this is more than enough. However, vertical scaling has a hard physical limit and becomes exponentially expensive.

While you can scale SQL horizontally via Sharding (partitioning data across multiple servers), it is notoriously difficult. You lose the ability to easily perform cross-shard JOINs, and rebalancing data when a shard gets full is a massive operational headache.

NoSQL databases scale horizontally out-of-the-box. Systems like Cassandra and DynamoDB use Consistent Hashing to distribute data evenly across hundreds of cheap nodes. If you need more storage or throughput, you simply add another node to the cluster, and the system automatically rebalances.

2. Data Modeling: Normalization vs Denormalization

  • SQL uses Normalization: Data is divided into multiple tables to eliminate redundancy. If a user changes their address, you update it in one place. The trade-off is that reading data requires CPU-intensive JOIN operations.
  • NoSQL uses Denormalization: Data is duplicated and grouped together based on how it is read. Instead of joining a User table and an Orders table, a Document database might embed the recent orders directly inside the User document. This makes reads blazing fast but means updates are more complex (you might have to update the same address in multiple documents).

3. Consistency vs Availability (CAP Theorem)

The CAP theorem states that a distributed data store can only guarantee two out of three: Consistency, Availability, and Partition Tolerance. Since network partitions (P) are inevitable in the real world, you must choose between Consistency (C) and Availability (A).

  • SQL databases generally choose CP or CA (in single-node setups). If a network partition occurs in a distributed SQL cluster, it will refuse writes to prevent data inconsistency.
  • NoSQL databases often choose AP. If a node goes down, the system will still accept writes. The trade-off is Eventual Consistency: two users might temporarily see different data until the nodes sync up.

4. Common Failure Modes

  • SQL - Connection Pool Exhaustion: Relational databases have a hard limit on concurrent connections. A sudden spike in microservice traffic can exhaust the connection pool, causing cascading failures across the system.
  • NoSQL - Hot Partitions: In distributed NoSQL, data is routed to nodes based on a Partition Key. If you choose a bad key (e.g., partitioning a global app by country, where 80% of your users are in India), one node will be overwhelmed with traffic while the others sit idle.
  • NoSQL - Split-Brain: In AP systems, if the network splits, two halves of the cluster might accept conflicting writes. Resolving these conflicts (e.g., using Vector Clocks or Last-Write-Wins) can lead to silent data loss if not handled carefully.

How it shows up in real systems

Let's look at how the mental model of querying changes between SQL and NoSQL. Imagine we are building an e-commerce dashboard and need to fetch a user's profile along with their recent orders.

In SQL, we rely on relationships and joins. In NoSQL (specifically a Document store like MongoDB), we rely on denormalized, aggregated documents.

def get_user_dashboard(user_id):
    # SQL: Requires joining normalized tables
    sql_query = """
        SELECT u.name, u.email, o.item_name, o.price
        FROM users u
        JOIN orders o ON u.id = o.user_id
        WHERE u.id = %s
    """
    
    # NoSQL (Document): Single fetch of an aggregated document
    # The orders are embedded directly inside the user document
    nosql_query = {"_id": user_id}
    return db.users.find_one(nosql_query)

Notice how the NoSQL approach requires less application-level mapping and fewer database operations at read time, but relies entirely on the data being pre-structured (denormalized) correctly at write time.

Interview questions

Here are the most common database-related questions asked in system design interviews, along with model answers.

1. "Design a database for a URL shortener. Would you use SQL or NoSQL?"

Model Answer: I would use a NoSQL Key-Value store like DynamoDB or Redis (with persistent storage). A URL shortener is fundamentally a massive hash map (short_url -> long_url). There are no complex relationships or joins required. Furthermore, URL shorteners are incredibly read-heavy (often a 100:1 read-to-write ratio). A Key-Value store provides single-digit millisecond latency for simple lookups and scales horizontally effortlessly to handle millions of requests per second.

2. "How do you handle transactions spanning multiple NoSQL documents?"

Model Answer: Traditionally, NoSQL databases do not support multi-document ACID transactions (though MongoDB added this in v4.0). If strict multi-entity transactions are required, it usually indicates we should be using an SQL database. However, if we must use NoSQL, we can implement the Saga Pattern at the application layer, where we execute a sequence of local transactions and apply compensating transactions (rollbacks) if a step fails. Alternatively, we can redesign our data model to embed all related data into a single document, as NoSQL databases do guarantee atomic updates at the single-document level.

3. "When would you choose Cassandra over MongoDB?"

Model Answer: I would choose Cassandra for write-heavy, time-series, or append-only workloads, such as logging IoT sensor data, storing chat messages, or tracking user activity streams. Cassandra uses an LSM-tree storage engine, which makes writes incredibly fast (O(1) sequential disk appends). MongoDB is better suited for read-heavy workloads with complex, unstructured data, like product catalogs or content management systems, where we need flexible indexing.

4. "What is the impedance mismatch problem?"

Model Answer: Impedance mismatch refers to the friction between object-oriented programming languages (which use objects, lists, and nested structures) and relational databases (which use flat tables and rows). Developers have to write complex ORM (Object-Relational Mapping) code to translate between the two. Document NoSQL databases solve this by storing data in JSON-like formats, which map directly to objects in code.

5. "How do you scale a relational database before resorting to sharding?"

Model Answer: Sharding is a last resort. Before sharding, I would:

  1. Optimize queries and add Indexes: Ensure no full table scans are happening.
  2. Scale vertically: Upgrade the database server's CPU, RAM, and SSDs.
  3. Implement Caching: Put Redis or Memcached in front of the database to absorb read traffic.
  4. Use Read Replicas: Route all SELECT queries to asynchronously updated read replicas, keeping the primary node dedicated entirely to INSERT/UPDATE/DELETE operations.

6. "What happens if a NoSQL node goes down during a write?"

Model Answer: It depends on the consistency level configured by the client. In systems like Cassandra, you can set a Write Consistency Level. If set to ONE, the write succeeds as long as one replica acknowledges it, and the downed node will catch up later via hinted handoffs or read repair. If set to QUORUM, a majority of replicas must acknowledge the write. If enough nodes are down that a quorum cannot be reached, the write will fail to protect data integrity.

Common mistakes

  • Ignoring the data access pattern: The biggest mistake candidates make is choosing a database based on the data itself rather than how the data is queried. Always ask the interviewer: "What are the most frequent read and write queries?"
  • Thinking NoSQL means "No Schema": NoSQL databases are technically "schema-on-read" rather than "schema-on-write". The data still has a structure, but the enforcement of that structure is pushed from the database layer up to your application code. If your application code expects a price field to be an integer, and the database returns a string, your app will crash.
  • Forgetting about indexing in NoSQL: Just because MongoDB is NoSQL doesn't mean it magically finds data instantly. If you query a Document database on an unindexed field, it will perform a full collection scan, which is just as disastrous as a full table scan in SQL.
  • Over-engineering: Don't propose a complex, multi-region Cassandra cluster for a startup's MVP. Start with a robust SQL database like PostgreSQL, explain its limits, and discuss how you would migrate to NoSQL or cache layers only when those limits are breached.

Mock interview

Can you explain it when someone pushes back?

Interviewers rarely ask for a definition. They ask why you'd pick this over that, and what breaks at ten times the load. A mock round finds those gaps before the real one does.

  • A question on your own project, then a design problem
  • The interviewer probes the parts you skim over
  • A scored report that quotes your answers and says what to fix
Start a mock design round Voice or text. Pause whenever you need to.

Applying somewhere? Start with the company filled in

Go deeper elsewhere

The best material we've found on these topics.

Practise this

Reading builds understanding. Practice makes it stick.

Keep reading

All articles
System design•intermediate

Database sharding and replication

13 min read
System design•beginner

Scaling a web app from one server to millions

11 min read
System design•intermediate

Rate limiting algorithms explained

14 min read