SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
  • Common Database Types
  • SQL vs NoSQL
  • ACID Transactions
  • B-Trees and B+ Trees
  • LSM Trees
  • Transaction Isolation Levels
  • Locking and MVCC
  • Normalization
  • OLTP vs OLAP
  • BASE and PACELC
  • Write-Ahead Log (WAL)
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Data and Storage/Database Basics

SQL vs NoSQL

Tables with strict rules, or flexible shapes that scale out? How to choose.

โฑ 14 min readBeginnerMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

SQL (relational) databases keep data in tables with a fixed shape and strong safety rules. NoSQL is a loose name for everything else: flexible shapes, and usually an easier way to spread data over many machines.

  • SQL: tables, joins, transactions. Great for connected, important data.
  • NoSQL: documents, key-value, wide column, graph. Great for flexible or huge data.
  • It is not a fight. The line is blurry, and many systems use both.
  • Start from the access pattern, size and correctness needs, not from fashion.

02Concept: What is it?

SQL stands for Structured Query Language, the language used to ask relational databases questions. A relational database stores data in tables. Every row has the same columns, and tables link to each other through keys.

NoSQL means โ€œnot only SQLโ€. It covers many designs that do not use the classic table model. Most of them trade some of SQL's strict rules for flexibility or easy scaling.

Same data, two shapes
SQL: tables
๐Ÿ‘คusersid, name
๐Ÿงพordersid, user_id, date
๐Ÿ“ฆorder_itemsorder_id, product_id, qty
NoSQL: one document
{
  "order": 1001,
  "user": { "name": "Asha" },
  "items": [
    { "product": "pen", "qty": 2 },
    { "product": "book", "qty": 1 }
  ]
}
SQL splits the data into tables and joins them back. A document store keeps the whole order together in one record.
๐Ÿง The real difference
SQL puts the rules in the database (shape, keys, transactions). NoSQL often moves more of the rules into your application, in exchange for freedom and scale.

03Real-Life Example

๐ŸตThe School Register vs the Notice Board
A school keeps a register: one printed form, same columns for every student, checked by the office. It is strict, but you can always answer questions like โ€œwhich students in class 5 owe fees?โ€. A notice board is the opposite. Anyone can pin anything, in any shape. It is quick and flexible, and the board can be as big as you want. But it is hard to ask exact questions across it.
School
Databases
Register with fixed columns
SQL table with a schema
Office clerk who checks every entry
Constraints and transactions
Looking up a student across fee and class registers
A join
Notice board with any kind of note
Document / NoSQL store
Adding another board for another wing
Scaling out (more machines)
One big register in one office
Scaling up (a bigger single machine)
Two ways to grow
Scale up (vertical)
๐Ÿ–ฅ๏ธSmall server
โ†’โ†“
๐Ÿ–ฅ๏ธBig servermore CPU, RAM, disk
Scale out (horizontal)
๐Ÿ–ฅ๏ธNode 1
๐Ÿ–ฅ๏ธNode 2
๐Ÿ–ฅ๏ธNode 3
SQL traditionally grows up first. Many NoSQL systems were designed to grow out from the start.

04Why Do We Need It?

๐ŸงญA big early decision
Moving data from one kind of database to another later is slow and risky.
๐Ÿ›ก๏ธCorrectness
Money, stock and bookings need strong rules. Some stores give them, some do not.
๐Ÿ“ˆScale
How far you can grow, and how hard it is to grow, differs a lot.
๐ŸงฑChange
Fast-changing products need a shape that is easy to alter.
๐Ÿ’ธCost and skills
Teams already know SQL. A new store costs learning time and operations work.
๐Ÿ—ฃ๏ธInterviews
Almost every design question asks you to pick a database and defend it.
The question is never โ€œwhich is better?โ€. It is โ€œwhich one fits how this data is used?โ€.

05Where Do We Use It?

Where SQL usually wins

๐ŸฆPayments and ledgers
Every cent must add up.
๐Ÿ›’Orders and inventory
Many linked tables and exact counts.
๐Ÿ“ŠReports and analytics queries
Joins, groups and sums across data.

Where NoSQL usually wins

๐Ÿ“ฑActivity feeds and chat
Huge writes, simple reads by key.
๐Ÿ“กIoT and logs
A flood of simple events.
๐Ÿ“šCatalogs and content
Items with very different fields.

06Types / Parts / How It Works

Side by side

SQL (relational)NoSQL
Data shapeTables, fixed columnsDocuments, key-value, wide column, graph
SchemaDefined first (schema-on-write)Flexible, often checked by the app (schema-on-read)
RelationshipsForeign keys and joinsEmbed data, or link by id in app code
TransactionsFull ACID across rows and tablesVaries. Often per record, some now support more
ScalingScale up first. Scale out with read replicas, sharding or newer distributed SQLDesigned to scale out
ConsistencyStrong by defaultOften tunable, sometimes eventual
Query powerSQL: very rich and ad hocDepends. Best at queries you planned for
ExamplesPostgreSQL, MySQL, SQL Server, OracleMongoDB, Cassandra, DynamoDB, Redis, Neo4j
SQL
Rules first
  • Data is checked on the way in
  • Joins answer questions you did not plan
  • Multi-row transactions are normal
  • Splitting over machines takes real work
NoSQL
Flexibility and scale first
  • Add a new field with no migration
  • One read can return a whole record
  • Many are built to spread over machines
  • You design for the queries you know
Design thinking: tables first or queries first?
SQL thinking
๐ŸงฉModel the datanormalise
โ†’โ†“
โ“Ask any queryjoins
NoSQL thinking
โ“List the queriesaccess patterns
โ†’โ†“
๐ŸงฉShape data for themdenormalise
SQL NoSQL
SQL designs start from the data and ask questions later. NoSQL designs usually start from the questions.
VisualizerSQL or NoSQL for this workload?Pick a ready-made workload, then drag writes per second and data size up. Watch the servers needed and the points shift.
Try a ready-made workload
Correctness needed
Evidence for each side (points added by your answers)
SQL 17
  • SQL +8Joins and ad hoc questions (level 4) are native in SQL
  • SQL +4Strict correctness: SQL gives multi-row transactions out of the box
  • SQL +2A stable shape: a fixed schema catches mistakes early
  • SQL +3Fits on one server: no need to split the data
Servers needed (one server is about 5,000 writes per second and 2 TB)
1
Servers needed
1
no splitting
SQL points
17
NoSQL points
0
SQL fits better here. One server is enough, so the strong rules and joins are worth more than easy scale-out.

A teaching model with made-up weights and round numbers. Real answers depend on hardware, the exact product and your team. Modern SQL databases can scale out (Spanner, CockroachDB, Vitess) and many NoSQL ones offer transactions, so the line is blurry.

07How to Use It / Steps / Implementation

How to choose

  1. 1
    Write the questions the app will ask
    For example: get a user by id, list their last 20 orders, total sales per month.
  2. 2
    Check how connected the data is
    Many links between things point to SQL. Self-contained records point to documents.
  3. 3
    Decide how strict it must be
    If two writes must never disagree (stock, balance), you want transactions.
  4. 4
    Estimate scale honestly
    One modern SQL server can handle a lot, often thousands of writes per second and terabytes of data. Do not scale out before you must.
  5. 5
    Think about change
    If the shape changes weekly, a flexible schema saves effort. If it is stable, a fixed schema protects you.
  6. 6
    Prefer the boring choice
    PostgreSQL or MySQL is the safe default. Pick NoSQL for a named reason.
  7. 7
    Mix when it helps
    SQL for the core, a key-value store for hot reads, a search engine for text. Keep one source of truth.
๐Ÿ’กA line that works in interviews
โ€œI would start with PostgreSQL for orders because we need transactions and joins. For the activity feed, which is huge and simple, I would use a wide column or key-value store.โ€

08Key Terms to Know

TermMeaning in easy words
SQLThe standard language for asking relational databases questions
NoSQLA broad name for non-relational databases: not only SQL
SchemaThe agreed shape of the data: columns, types and rules
JoinCombining rows from tables by a shared key
NormalisationSplitting data so each fact is stored once
DenormalisationCopying data on purpose so one read gets everything
Vertical scalingMaking one machine bigger
Horizontal scalingAdding more machines
Eventual consistencyCopies may differ for a short time but agree later
Distributed SQLSQL databases built to spread over many machines (Spanner, CockroachDB)

09Pros, Cons and Trade-offs

SQL

โœ… Pros
  • Strong transactions and rules
  • Powerful, flexible queries and joins
  • Mature tools and huge community
  • Data checked on the way in
โš ๏ธ Cons
  • Schema changes can be slow on huge tables
  • Scaling writes across machines is hard
  • Rigid shape for messy data
  • Joins get costly over big, split data

NoSQL

โœ… Pros
  • Flexible shapes
  • Built to spread over many machines
  • Very fast for known access patterns
  • Easy to start
โš ๏ธ Cons
  • Weaker or limited transactions
  • Few ad hoc queries and joins
  • Data copies must be kept in step by you
  • Each product works differently

Trade-offs

ChoiceWe gainWe lose
Fixed schemaSafety and claritySlower changes
Flexible schemaSpeed of changeBugs from inconsistent data
Normalised dataNo duplicate factsJoins on every read
Denormalised dataFast readsMore writes and risk of drift
Strong consistencyAlways correctMore latency, harder to spread
Eventual consistencySpeed and availabilityReaders may see old data

10Common Problems and Mistakes

Common mistakes

  1. Picking NoSQL because โ€œSQL does not scaleโ€. A single SQL server goes surprisingly far, and many big companies run on sharded MySQL or PostgreSQL.
  2. Picking NoSQL to avoid design. โ€œNo schemaโ€ really means the schema lives in your code, and every old document shape must still be handled.
  3. Using SQL for a firehose on one box. A huge write rate on a single primary will hit a wall.
  4. Modelling a graph in joins. Many hop-by-hop joins get very slow. Consider a graph database.
  5. Re-creating joins in app code. If you need many joins in NoSQL, you probably picked the wrong tool.
  6. Assuming a label tells you the rules. Some NoSQL stores have transactions. Some SQL setups are eventually consistent across replicas. Read the docs.

Things to watch

๐Ÿ”€Blurry line
PostgreSQL stores JSON. MongoDB has multi-document transactions. Check current features.
๐ŸงฎHot partitions
Scale-out stores slow down if one key gets all the traffic.
๐Ÿ”Migrations
Old documents with old shapes must still work after the code changes.
๐ŸงญLock-in
Some NoSQL query styles are specific to one product.

11Real-World Examples

๐Ÿ˜PostgreSQL and MySQL
Run a very large share of the web. Companies scale MySQL with sharding layers such as Vitess (general idea).
๐ŸƒMongoDB
A document database popular for content and catalogs with changing fields.
โšกDynamoDB
A managed key-value and document store on AWS built for steady speed at huge scale.
๐Ÿ›๏ธCassandra
A wide column store used for huge write loads across data centres.
๐ŸŒSpanner and CockroachDB
Distributed SQL: SQL and transactions with scale-out. It shows the line is blurry.
๐ŸงฉMixed stacks
Most large products use both: SQL for money and accounts, NoSQL for feeds, caches and search.
๐Ÿ“Note
These are general examples. Features and best practice change from version to version.

12Related Topics to Read Next

Common Database Typesโ†’

The full family map.

Relational Databasesโ†’

SQL in detail.

Document Databasesโ†’

The most common NoSQL style.

ACID Transactionsโ†’

The safety promises SQL is known for.

CAP Theoremโ†’

Why spreading data forces consistency choices.

Denormalizationโ†’

Copy data on purpose to make reads cheap.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • โœ”SQL: tables, fixed schema, joins, ACID. Safe default.
  • โœ”NoSQL: flexible shapes, built to scale out, query by known pattern.
  • โœ”Pick SQL for: connected data, money, reports, ad hoc questions.
  • โœ”Pick NoSQL for: huge writes, changing shape, simple key access.
  • โœ”Myth: โ€œSQL cannot scaleโ€. It can, with more work (replicas, sharding, distributed SQL).
  • โœ”Myth: โ€œNoSQL has no schemaโ€. The schema moves into your code.
  • โœ”Mix: SQL core plus cache, search or feed stores. Keep one source of truth.
  • โœ”One line: โ€œChoose by access pattern, scale and correctness, and default to SQL unless you can name a reason.โ€
โ† Previous
Common Database Types
Next โ†’
ACID Transactions