SQL vs NoSQL: How to Choose a Database (System Design)

Pick a database by the queries it must serve. When SQL, document, key-value, wide-column or graph stores fit, with system design interview examples.

SQL vs NoSQL: common questions

When should I use NoSQL instead of SQL?

When a named access pattern needs it: huge write volume on a simple key, flexible documents read whole, or wide time series. Start relational and move one dataset when a number demands it.

Is NoSQL faster than SQL?

Not in general. A key lookup is fast in both. NoSQL stores scale out more easily by giving up joins and some consistency.

PostgreSQL or MongoDB for an app with 1 million users?

User count does not decide it: either handles 1 million users comfortably. Choose by data model, access pattern, consistency needs and team experience. Postgres fits relational data with joins and transactions, and JSONB covers flexible fields; MongoDB fits document-shaped data with changing schemas that is mostly read by key.

Related chapters

Keep learning

Overview

write scale flexible schema query by key only Wallet & orders payments app Money moves must be all-or-nothing (ACID). CHECK (balance >= 0) and foreign keys stop bad rows. MySQL, or a distributed SQL store (CockroachDB, Spanner) at huge scale Cassandra: no multi-row transactions Chat messages by conversation Partition by conversation, sort by time: one partition read per screen. DynamoDB (PK conversation, SK timestamp), ScyllaDB One Postgres primary at billions of messages a day Session cache login tokens GET session:7f3a · SET … EX 1800 In memory: sub-millisecond GET by session id. Memcached, DynamoDB with TTL A SQL table hit on every single request Product search "spicy paneer near me" search index (derived) match: "spicy paneer" + filter: open_now, rating ≥ 4 Inverted index: fast full-text, typo-tolerant, ranked results. Copy of the data, fed from Postgres via CDC or Kafka. LIKE '%paneer%' on a big table: full scan people you may know MATCH (me)-[:FRIEND*2]-(fof) RETURN fof Deep, variable-length paths are one short query. Key-value store: you would do the hops in app code Metrics stream rider GPS / sensors Append-only writes, chunked and compressed by time. Built-in time buckets, downsampling and retention. InfluxDB, Prometheus (metrics), ClickHouse Plain rows in the orders database: bloats it fast ✓ must have · ~ somewhat · ✕ not needed system design · core concepts SQL vs NoSQL: picking a database in an interview Pick the store from the queries you must serve, not from a slogan.

1. The problem: “which database?”

“NoSQL, because it scales.” Scales what: reads, writes, data size? For which query? The interviewer now doubts every later choice. “Postgres. Orders need a transaction.” Then: “Chat messages are read by conversation_id only, at 100 K writes/s, so Cassandra for those.” A good answer names the access pattern: which key you read by, how often, and what must stay correct.

2. Relational: tables, joins, rules

Data lives in tables with fixed columns. Rows point to each other by id (foreign keys). One query, three tables, joined at read time Biryani House Dosa Point Combine tables in any query. Foreign keys, UNIQUE, CHECK reject bad data. Many rows change together, or none do. Ad-hoc queries New question? Write SQL, add an index. Scaling is possible, but mostly up, not out. Scale up bigger machine, more RAM Read replicas smaller tables, same server Each step out costs more effort. Sharding loses cross-shard joins and transactions. primary takes every write (unsharded) replicas share the reads

3. The NoSQL families

“NoSQL” is not one thing. It is four different data models, each fast at one shape of query. Redis · DynamoDB GET / PUT by one key. Sessions, carts, rate-limit counters. JSON-like documents with nested fields. Restaurant menus that vary per restaurant. Rows grouped by partition key, sorted inside. Chat history, activity feeds. Nodes and edges, queried by walking links. Friends, fraud rings, routes. Two more are usually derived stores: copies built from the main database, not the source of truth. Search index Full-text, typos, ranking, filters. Dish and restaurant search. TimescaleDB · InfluxDB Append-only points by time. Rider GPS, latency metrics. The same order, stored four ways what is stored fast query get by id get by id or any indexed field partition user_id=7 → rows sorted by created_at Asha’s latest orders (Asha)-[:PLACED]->(981)-[:FROM]->(Biryani House) who ordered from where

4. Side by side

flexible schema Relational (Postgres) Key-value (DynamoDB) Document (MongoDB) Wide-column (Cassandra) Graph (Neo4j) Search (Elasticsearch)

Schema: enforced or flexible

Schema on write (SQL) The database rejects a row with a missing price. Changes need a migration. Schema on read (document) Any shape is accepted. Every reader must handle old and odd shapes.

Joins vs design-the-table-around-the-query

In Cassandra or DynamoDB you list the queries first. Then you build one table per query. Query 1: messages in a chat Query 2: a user’s chats Store each fact once. Join at read time. New queries are cheap to add. Wide-column / DynamoDB Duplicate data per query (denormalize). Reads are one partition. A new query often means a new table + backfill.

Transactions: how far does one reach?

atomic across Postgres / MySQL any rows, any tables many documents (4.0+) up to 100 items (TransactWriteItems) costs 2× capacity one partition (lightweight tx) one node (MULTI / Lua) no rollback on error

Scale: built in or added

Added later (SQL) You choose a shard key and add routing (Vitess, Citus) when one primary is full. Built in (Cassandra, DynamoDB)

Consistency: what you get by default

default read can ask for Postgres primary latest committed replicas are behind (async lag) eventually consistent per query: ONE / QUORUM / ALL QUORUM writes + reads ⇒ read your writes about 1 s behind (refresh) never the source of truth

6. The decision path

Access pattern read by what key? joins? full text? must it be exact? money, stock, seats writes/s, data size, growth Start with Postgres or MySQL. Move a dataset out only when a concrete pattern or number demands it. you hear it points to “book the last seat, never double-sell” SQL with a transaction or row lock “always read by one id, 1 M writes/s” Cassandra / DynamoDB “read the same thing a million times” Redis cache in front of SQL “search by words, typos, filters” Elasticsearch fed from SQL “friends of friends, paths” graph store (or SQL for 1–2 hops) Say it like this “Orders go in Postgres: we need a transaction across order, payment and stock. Order history is read by user_id, so I index that.”

Interview: “PostgreSQL or MongoDB for an app with 1 million users?”

Asked by @mayuri_3015 The framing is the trap. User count does not decide this. A million users who each make 50 requests a day is about 50 M requests a day: roughly 600 a second on average and a few thousand at peak. One well-indexed Postgres or MongoDB server handles that comfortably. What decides it: The data model: are there relations between things (users, orders, payments), or self-contained documents? How the data is read: joins and ad-hoc filters, or mostly “fetch this one document by its key”? Consistency: do several records have to change together (money, stock, seats)? The team: the database your team already runs well is worth a lot. When each one fits Best for Relational data: joins, constraints, multi-row transactions Document-shaped data with a changing schema, mostly read by key Flexible fields JSONB columns, which you can index, for the parts that vary Native: every document can have its own shape Transactions across records Core feature 1 million users Say it like this

7. Lab: pick the store

Pick a workload. See the store, why, and which needs drove the choice.

8. Polyglot persistence: one app, several stores

source of truth Orders, payments, users. Sessions, menus, rider location. Restaurant and dish search. event log OrderPlaced, OrderDelivered events. COMMIT order 981 via outbox or CDC (Debezium) index restaurant stats a moment later Copies are updated from events, so they lag a little. Never write to two stores in one request and hope. Cost of more stores More systems to run, back up and keep in sync. Interview rule Add a store only when you can name the query it serves.

Remember

Default to Postgres / MySQL Name the access pattern first Wide-column: one table per query Money and seats need transactions Search and cache are copies 1 Start with SQL Joins, constraints and ACID for free. Replicas and caching go a long way. 2 Justify every switch with a query “Read by conversation_id at 100 K writes/s” beats “NoSQL scales”. 3 Mix stores, one source of truth Orders in SQL, cache in Redis, search in Elasticsearch, events in Kafka. → Go deeper: ACID, isolation levels, read replicas, sharding, querying by a non-key column, quorum reads and writes, transactions across machines, designing a food app, Redis, Kafka.

More courses

  • Jobs, linked to lessons — Browse jobs where every requirement links to the chapter that teaches it. See how ready you are, how long the gap takes to close, and which listings look stale.
  • Match a job post to courses — Paste a job post. Each skill is matched to a track here and put in learning order, foundations first.
  • React patterns from open source — Patterns extracted from Material UI, Radix, React Aria, React Hook Form, Redux Toolkit, TanStack, and Next.js — not slides about hooks.
  • Databases in depth — How a query becomes work. Indexes, isolation, locks, and the plans that explain why a page is slow — not an ORM tour.
  • NestJS: build a real API — One ticket-booking API, built in order: a plain Node server first, then NestJS modules, validation, a real database, and the features real clients lean on.
  • Microservices — Microservice patterns one diagram at a time: how to split a monolith, how services talk, and how data stays consistent without distributed transactions.
  • Kafka — A beginner-to-senior path through event logs, reliable delivery, production operations, and disaster recovery.
  • AI engineering for software engineers — Eight free reads, in order, for software engineers moving into AI: when to build an agent, how to build one, how to test it, and how the model works underneath.
  • Frontend system design — How a UI is sliced when it is a product, not a page: ownership of state, cache, routes, and what happens when the network lies.
  • TypeScript in depth — The type system as a design tool. Inference, narrowing, generics, and the errors that mean the model is wrong — not a catalog of utility types.
  • CSS in depth — See the box, then the page. Visual chapters from the box model through Flexbox surprises, Grid, selectors, and units, then backgrounds, shapes, and visual effects, each with a playground.
  • Accessibility — Foundations first (WCAG in plain words, semantic HTML, lists, alt text), then hands-on HTML labs, a full pass of WAI-ARIA 1.3, and a final fix-the-page challenge.
  • Docker — What an image is, why layers cache, and how containers find each other on a network.
  • Redis — Fifteen Redis patterns, one picture each: cache, session, lock, counter, rate limiter, queue, and when Redis is the wrong tool.
  • Kubernetes — Kubernetes from zero to operators: why it exists, Pods, Deployments and Services, then configuration, networking, storage, scheduling, scaling and security.
  • AWS — AWS networking in plain English. A VPC is a gated housing society: streets are subnets, the Internet Gateway is the main gate, and a route table is the signboard.
  • Networking: the NetRoute game — NetRoute is a packet logistics game. You wire up computers, switches, routers, firewalls and gateways, set each device, and watch glowing packets travel. If a packet gets dropped, the game shows you which header field was wrong.