SQL vs NoSQL

Two ways to organize and store data, each suited to different problems.

What is it?

Databases don't all organize data the same way.

- SQL databases are relational. They store data in strict tables with fixed columns and are very good at keeping relationships between data consistent. (SQL, Structured Query Language, is the language used to query them, and the name stuck to the whole category.) - NoSQL ("not only SQL") databases are more flexible. They store data as loose documents, key-value pairs or other shapes, trading some structure and consistency for flexibility and easier scaling across many machines. Most still support querying, just not with SQL.

Neither is always "better". The right choice depends on how structured your data is and how it needs to scale.

Explain like I'm 10

A SQL database is like a set of strict spreadsheets with fixed columns: great for consistency. A NoSQL database is like a stack of index cards where each card can have whatever fields it needs: great for flexibility.

Examples

The same data, two different shapes

-- SQL: fixed columns, a strict table
-- users(id, name, email)
SELECT * FROM users WHERE id = 1;

// NoSQL (document-style): flexible shape per document
{
  "id": 1,
  "name": "Amara",
  "email": "amara@example.com",
  "preferences": { "theme": "dark" } // easy to add, no schema change needed
}

How it works

SQL databases enforce a schema (every row in a table has the same columns) and are built around relationships between tables: a user has many orders, an order has many items.

NoSQL databases usually don't enforce a fixed schema, so each record's shape can vary. They often give up some cross-record consistency to make it easier to spread data across many servers.

Why does it exist?

Some data is naturally tabular and full of relationships (financial records, inventory), which suits SQL's structure and guarantees. Other data is less structured or must scale to huge volumes across many servers (logs, activity feeds), which suits NoSQL's flexibility.

When to use it

Choose SQL when data is naturally tabular, relationships matter (orders belong to users, items belong to orders) and you want strong consistency.

Choose NoSQL when the data's shape varies or changes often, or it needs to scale out across many machines more easily than one relational database can.

When not to use it

Don't pick NoSQL because it feels more modern. If your data is truly relational, a document store often means rebuilding SQL's features yourself.

And don't force rigid SQL tables onto data that keeps changing shape: frequent schema migrations become a maintenance burden.

Common mistakes

  • Assuming NoSQL is always 'faster' or 'more modern'. It's a different trade-off, not an upgrade.

  • Using a rigid SQL schema for data that changes shape constantly, causing painful migrations.

  • Using NoSQL for data with many strict relationships, then rebuilding relational logic by hand in app code.

Practice exercises

  1. Easy:

    List two kinds of data that fit naturally into SQL tables and two that fit better as flexible NoSQL documents.

  2. Medium:

    Explain what a 'schema' is and why enforcing one has both benefits and costs.

  3. Hard:

    Describe a case where you might use both a SQL and a NoSQL database in one app, and why.

Interview questions

What's the main structural difference between SQL and NoSQL databases?

SQL databases enforce a fixed schema and organize data into related tables. NoSQL databases usually allow flexible, schema-less structures like documents or key-value pairs.

When would you choose NoSQL over SQL?

When data doesn't fit neatly into fixed tables, needs to scale horizontally across many servers, or changes structure often.

Does choosing NoSQL mean giving up data consistency entirely?

No. But many NoSQL systems trade some strong consistency for availability and scalability, an approach called 'eventual consistency'.

What are the main categories of NoSQL databases, and what's each typically good at?

Document stores (e.g. MongoDB) suit flexible, nested records whose shape varies. Key-value stores (e.g. Redis, DynamoDB) suit simple, very fast lookups by one key. Wide-column stores (e.g. Cassandra) suit huge, sparse, write-heavy datasets. Graph databases (e.g. Neo4j) suit data defined mainly by relationships, like a social network.

Scenario: you're building a product catalog where each category has wildly different attributes — a book has an author and ISBN, a TV has screen size and resolution. SQL or NoSQL?

A NoSQL document store fits: each product stores only its own fields. In SQL you'd need a table with dozens of mostly-null columns, or an awkward entity-attribute-value pattern that rebuilds flexible storage on a rigid one.

Scenario: you're building the ledger for a banking app that must guarantee an account's balance is never double-spent across two concurrent transfers. SQL or NoSQL?

SQL. This needs strong multi-row ACID transactions: a debit and credit both apply or neither does, and no other transaction can see a half-applied state. Many NoSQL databases don't support multi-document transactions, or added them later at a real performance cost because they work against their scaling model.

Why do most NoSQL databases avoid supporting joins, and what does that push you to do instead?

When data is spread across many machines, a join may need data from several nodes, which is expensive. So NoSQL data is usually denormalized: related data is embedded in the document the query needs, duplicated rather than joined at read time.

What's the difference between "schema-on-write" and "schema-on-read," and which philosophy does each side favor?

SQL is schema-on-write: the data's shape is checked at insert time. NoSQL is usually schema-on-read: data is stored as-is and whatever reads it must interpret its shape, which moves validation from the database to the app.

What does BASE (as a contrast to ACID) stand for, and what philosophy does it represent?

Basically Available, Soft state, Eventually consistent. It's the philosophy behind many NoSQL systems: stay available and responsive rather than guarantee every read is up to date.

Scenario: you need to store hundreds of millions of IoT sensor readings per day, mostly appended once and rarely updated, queried by device and time range. What fits, and why?

A wide-column or time-series NoSQL store. It's built for very high write throughput and partitions naturally by device id and time. The workload needs fast, well-partitioned appends and range scans, not relational joins.

What's a real cost of denormalizing data into a NoSQL document that a SQL-background developer might not expect?

The same fact can be copied into many documents (e.g. a username in every post by that user). Changing it means updating every copy, not one row in one place.

Why can adding an index be a more deliberate, upfront decision in a NoSQL database than it typically is in SQL?

Many NoSQL databases lack a general query planner that optimizes any ad hoc query the way SQL does. You often design indexes around known access patterns in advance, and a query that doesn't match an index can be slow, or even rejected at scale.

What does "polyglot persistence" mean, and what's a realistic example?

Using different databases for different parts of one system instead of forcing one database to do everything. For example: SQL for orders and payments that need strong transactions, a document store for a flexible content catalog, and an in-memory key-value store like Redis for sessions.

Scenario: your document store doesn't support transactions across multiple documents. How do you still guarantee that a related pair of writes always happens together?

Two common options. Restructure so what must be atomic lives in one document (embed instead of reference), since a single-document write is still atomic. Or accept the multiple steps and add a compensating-action (saga-style) pattern in the app that detects and repairs a partly applied write.

Why is horizontal scaling often easier to achieve with NoSQL databases than with a traditional relational database?

Many NoSQL databases are designed for distribution from the start. Their data model discourages cross-node joins and transactions, so partitioning across machines doesn't fight the model. Relational databases were designed for a single node, with distribution (sharding, distributed SQL) added later at real complexity cost.

Common misconception: "NoSQL databases are always faster than SQL databases." Why is this wrong?

Speed depends on how well the data model and indexes fit the query pattern, not the category. A well-indexed SQL query on well-structured data can beat a poorly modeled NoSQL query, and vice versa.

Scenario: your app uses one SQL database for everything, and a new "notification history" feature needs to store an ever-growing, rarely-queried-in-detail log of every notification sent, at huge volume. Keep it in the same database?

Probably not as-is. Unbounded, high-volume, append-heavy data competing for the same database can slow the core transactional work. A store suited to that pattern (a NoSQL store, a cheaper storage tier, or a log/analytics system) usually fits better.

What's the practical impact of eventual consistency on a NoSQL-backed app's UI, and how do teams commonly work around it?

A user's own write may not show up if their next read hits a replica that hasn't caught up. Common fixes: "read-your-own-writes" routing (send the user's reads to the node they just wrote to), or update the UI optimistically from the write instead of waiting for a fresh read.

What's the difference between a key-value store and a document store, given both can look like "a big dictionary"?

A key-value store treats the value as an opaque blob: the database can't see or query inside it. A document store understands the value's structure and can query or index individual fields.

Why is choosing a good partition key in a NoSQL database often even more consequential than choosing a good index in SQL?

Most NoSQL databases route straight to a partition by that key and have no efficient ad hoc query or cross-partition join to fall back on. A bad key doesn't just make one query slow; it can make a whole access pattern expensive or unsupported.

Scenario: a social feature needs to find "mutual friends of these two users," potentially traversing several hops of relationships. What's purpose-built for this, and why would a relational database struggle?

A graph database, which follows direct pointers between connected nodes. A relational database needs repeated self-joins on a friendship table, and the cost grows quickly with each extra hop.

Does using a NoSQL database mean giving up data validation entirely?

No, validation just moves. Instead of a schema enforcing types and shape, the app code (or an optional schema-validation layer some NoSQL databases offer) makes sure documents have the expected shape.

What's a real downside of SQL's rigid schema for a product that's still evolving rapidly, like an early-stage startup?

Every new field needs a migration (ALTER TABLE), which can be slow or lock a large table, and the team must coordinate the change before using the field. In a document model, a new field can just start appearing in new documents.

What's the conceptual difference between "get this user's 5 most recent orders" in SQL versus in a document store?

In SQL, it's usually a join between users and orders that the database filters, sorts and limits. In a document store, you'd either embed recent orders in the user document, or query a separate orders collection with a compound index on (userId, createdAt). The app, not the database, relates the two.

How does the CAP theorem relate to why many NoSQL databases default to eventual consistency?

CAP says a distributed system can't guarantee both perfect consistency and availability during a network partition; it must give one up. Many NoSQL databases were built to keep serving requests when parts of the cluster can't talk, so they favor availability and accept eventual consistency.

Follow-up: does that mean SQL databases can't scale horizontally at all?

No. Modern distributed SQL databases shard and replicate data while keeping relational semantics and stronger consistency. They've been harder to build and are more complex to run than NoSQL's original model, but "SQL doesn't scale" is an oversimplification.

What does it mean for a wide-column NoSQL table to be "sparse," and why is that useful?

Rows in the same table can have completely different sets of columns, unlike SQL where every row has every column (even if null). This saves storage when most rows use only a small, varying subset of many possible columns.

Scenario: you need full-text search across product descriptions with typo tolerance and relevance ranking. Is a general-purpose SQL or NoSQL database the right primary tool?

Neither, really. A dedicated search engine (like Elasticsearch, itself a specialized document store) is built for tokenizing, ranking and fuzzy-matching text. Use it alongside your main database, not instead of it.

What's a common trap when migrating an existing relational schema "as-is" into a NoSQL document store?

Turning each SQL table into its own collection and still joining them at query time. You lose the document model's strengths (it has no efficient joins) and keep none of SQL's transactional guarantees. Redesign the schema around the app's real query patterns instead.

Why might a team choose NoSQL specifically for a very write-heavy workload over SQL?

Many NoSQL databases spread writes across many nodes with little coordination, giving very high write throughput. A single relational database (before sharding) sends all writes through one primary, which becomes the bottleneck.

How does handling "the data's shape changed yesterday" typically differ between the two systems?

In SQL, a shape change needs a migration, ideally versioned and run the same way in every environment, before old and new code can share the table. In a document store, existing documents don't change, so app code often handles both old and new shapes at once. Schema changes happen in the app layer instead of upfront.