SQL vs NoSQL: Which Database Fits Your Data?
Sign up for a food-delivery app and it saves your name, phone and address. Add a second address or a note for the rider, and it saves those too. Someone chose the database behind it. This lesson explains SQL vs NoSQL: the two broad families of databases, how they differ and how teams choose.
SQL databases: tables with a fixed shape
A relational database, as What Is a Database? showed, keeps data in tables of rows and columns and answers questions in SQL (Structured Query Language), so it is often called a SQL database. PostgreSQL and MySQL are well-known examples.
Each table has a schema: its declared shape, naming every column and the type of value it holds, such as text, a whole number or a date. You declare it before saving data, and the engine checks rows against it; PostgreSQL, for example, rejects a word in a number column. Changing the shape later is a deliberate step that affects every row.
Tables link through keys: a foreign key holds another table's primary key. A join combines linked tables into one answer, such as each order with its customer's name; SQL Basics teaches joins next. On a single server, relational databases also give strong consistency: once a change is confirmed, every later read sees it.
NoSQL: not only SQL
NoSQL covers databases that don't keep data in linked relational tables; the name is now usually read as "not only SQL". It spans four main kinds.
Document databases
A document database, such as MongoDB, stores each item as a JSON-like document, with details nested inside, like the address object in REST APIs and JSON. Documents sit in a collection, and they need not share the same fields.
The diagram stores three customers both ways. Notice the NULL cells, SQL's marker for "no value": every row gets every column. Each document holds only its own fields, and Ravi's two addresses fit as a list.
Key-value stores
A key-value store, such as Redis, saves each value under a unique key and returns it when you give that key, like a coat check's numbered ticket. Redis keeps data mainly in memory, so it is very fast, and can also save it to disk. It is a popular cache, a quick nearby copy of data, as What Is Caching? explains.
Wide-column stores
A wide-column store, such as Apache Cassandra, also has tables of rows and columns, but each row's partition key decides which machines hold it, so one table spreads across many. Cassandra has no joins, so you design each table around a question you plan to ask.
Graph databases
A graph database, such as Neo4j, stores nodes (things, such as people) and relationships (named links between two nodes, such as "follows"). It shines at questions that hop along many links, such as friends of friends.
The trade-offs
A flexible schema lets you add a field to new documents without touching old ones, which suits varied data such as products with different specifications. The checking moves into your code, which must cope with missing or misspelt fields; MongoDB offers optional schema validation when you want rules.
Horizontal scaling means adding machines to handle more load, instead of buying a bigger one, as Scaling Up vs Scaling Out explains. Many NoSQL stores were built for it: Cassandra rebalances data as machines join. Relational databases can scale out with read-only copies or by splitting tables across servers, but it usually takes more work.
Relational databases win when questions cross related data: which customers in Pune ordered tea last month? One query joins customers, orders and products. Document stores are usually shaped around the questions you expect, often copying details into several documents, so an unplanned question can be slow or awkward.
The table compares four of these kinds; notice that no column wins every row.
Consistency: ACID or eventual
A transaction, from lesson 5, saves a group of changes together or not at all. Relational databases such as PostgreSQL give transactions four guarantees, known as ACID:
- Atomicity: all the changes happen, or none do.
- Consistency: the data still obeys its rules, such as constraints.
- Isolation: transactions running at once don't see each other's unfinished changes.
- Durability: a confirmed change survives a crash.
Distributed stores keep copies of the data, called replicas, on several machines. Some offer eventual consistency: a change reaches every replica eventually, but meanwhile a lagging replica can return the old value. Cassandra's documentation calls it "an eventually consistent storage system". Not waiting for every copy keeps a store fast, and working when a machine fails: fine for a like counter, not for a bank balance.
The lines blur: MongoDB and Neo4j support ACID transactions, and a relational database's lagging read-only copy can serve old data too. Note that ACID's C means "obeys the rules", not "every copy agrees".
How to choose
Start with what one item looks like and how you will look things up. The flowchart turns those answers into a first guess. Notice that two of its three endings are relational, the usual default.
Many systems use both: a shop might keep orders and payments in PostgreSQL, a cache in Redis and product details in MongoDB. One database can even blend the two, since PostgreSQL can store JSON documents in a table column with its jsonb type.
Check yourself
A clinic app links patients, doctors and appointments, and a booking must never be half-saved. Which kind fits, and why?
Relational: the data is highly related through keys, and an ACID transaction saves each booking whole or not at all.
A shop sells phones, sarees and spices, each with very different details. Why might a document database suit its catalogue?
Each product can be one document holding only its own fields, instead of a table with dozens of mostly empty columns.
For a few seconds, a post shows different like counts on two phones. What is a likely cause, and is it a bug?
Probably eventual consistency: the phones read different replicas, and one lacks the latest change. It is an accepted trade-off, not a bug; the counts match once that replica catches up.