codequest / system design
Core concept 10 of 21

SQL vs NoSQL

Relational databases, key-value, document, wide-column and graph stores: what each is good at and when to pick it.

Start with SQL

Relational databases (PostgreSQL, MySQL) store rows in tables with a schema, support joins, and give you ACID transactions. They handle far more than people expect, often tens of thousands of queries per second on one well-sized primary with replicas. Unless you have a specific reason, a relational database is the safe default.

The NoSQL families

TypeGood atWatch out forExamplesTypical use
RelationalJoins, transactions, ad-hoc queries, strong consistencyScaling writes past one primary needs shardingPostgreSQL, MySQLUsers, orders, payments
Key-valueVery fast get/set by key, huge scaleNo queries beyond the keyRedis, DynamoDBSessions, caches, counters
DocumentFlexible JSON-like records, nested dataJoins and cross-document transactions are limitedMongoDB, FirestoreProduct catalogues, profiles
Wide-columnMassive write throughput, time-ordered dataDesign tables per query; limited ad-hoc queriesCassandra, HBase, BigtableChat messages, events, metrics
GraphTraversing relationships many hops deepNiche; harder to scale horizontallyNeo4jSocial graphs, recommendations
Search indexFull-text search, ranking, filtersNot a source of truth; kept in sync from the main storeElasticsearch, OpenSearchSearch boxes, log search

How to decide

  • Need transactions or relationships between entities? Relational.
  • Simple lookups by ID at huge scale? Key-value.
  • Enormous write volume, accessed by key and time? Wide-column.
  • Schema changes constantly and records are self-contained? Document.
  • Most real systems use several: Postgres as the source of truth, Redis as a cache, Elasticsearch for search, object storage (S3) for files.
"NoSQL scales, SQL doesn't" is outdated. The real trade-off is flexibility of queries versus how easily the data splits across machines.

In the interview

  • Pick the database per access pattern and say why ("messages are written constantly and read by conversation and time, so wide-column").
  • Keep files in object storage and only their metadata in the database.
  • Mention consistency needs: money stays in a database with transactions.