SQL vs NoSQL — Database

SQL stores every fact once in tables that point at each other by id. It is strong at JOINs, reports across the data (reports that read a lot of data at once)…

All through this track, Sunset Coffee has kept its orders in PostgreSQL and its cache in Redis. In the previous lesson, you also saw the same order stored whole in MongoDB. So which one should you use? The honest answer: it depends on which questions your app asks most often.

An SQL database (relational) keeps data in tables with a fixed schema, links those tables by id, and guarantees ACID transactions. NoSQL is the group of databases that don't keep data in relational tables: document (MongoDB), key-value (Redis), graph, and others. There is no "best". What decides is the access pattern: which questions your app asks the database most often, and which changes it writes most often. Remember the first two clerks in the Types of Database lesson. The first fills in ruled tables that point at each other by number (SQL). The second keeps one complete folder per order (document). The ruled tables are easy to use for summaries, such as adding up total sales. The folder is easy to use for taking out one whole order.

One feature, two models

The feature: Sunset Coffee's order history, with the same data as the rest of this track. Its data can be stored with two models (ways of arranging data). In SQL, the data is spread over four tables: customers, orders, order_items and products, and every fact is stored once. Budi's name, for example, is in one row only. In a document model (MongoDB), each order is one document holding the buyer's name and its items:

{ _id: 1, customer: { _id: 1, name: 'Budi' },
  items: [ { product: 'Milk Coffee', price: 450, qty: 2 },
           { product: 'Toast', price: 500, qty: 1 } ] }

This page's Lab runs four access patterns against both models: the SQL in real SQLite, the documents in a MongoDB simulation.

Reading one order

The "order #1" page needs the buyer's data and every item of the order:

SQL Document
Command 1 query with 3 JOINs db.orders.findOne({ _id: 1 })
What is read 6 rows from 4 tables 1 document

For fetching one whole thing, the document wins: everything is already in one place.

A report across the data

A report across the data reads a lot of data at once. One example is the question "Which product sells best?", which has to look at every order. In SQL, it takes one query with GROUP BY:

SELECT p.name, SUM(oi.qty) AS sold
FROM order_items oi
JOIN products p ON p.id = oi.product_id
GROUP BY p.id, p.name
ORDER BY sold DESC, p.name;

The result:

name sold
Milk Coffee 3
Milk Tea 1
Palm Sugar Milk Coffee 1
Toast 1

With documents, you need an aggregation pipeline with three steps: unpack the items array in every document into one document per item ($unwind), group by product ($group), then sort ($sort). The result can be the same, but questions across the data and JOINs are SQL's strength.

Changing data: Budi changes his name

Budi already has 40 orders, then changes his name to Budi Santoso:

UPDATE customers SET name = 'Budi Santoso' WHERE id = 1;

In SQL, Budi's name lives in one customers row only. 1 row changes, and all 40 of his orders show the new name through the JOIN. With documents, the name is copied into every order, so updateMany has to change 40 documents.

There's a second problem. In MongoDB, a change to one document is always atomic: that document changes completely, or not at all. But updateMany as a whole is not atomic. If the server stops halfway, some documents already say Budi Santoso and the rest still say Budi. In SQL, the changes inside a transaction all succeed or all fail: a transaction that never reached COMMIT is thrown away when the server starts again. MongoDB 4.0 and later has multi-document transactions too (one transaction for many documents). But they are heavier to run, and they don't happen automatically: you have to use them yourself.

Changing the shape of the data

Sunset Coffee wants to add a note (note, such as "less sweet") to orders.

A flexible schema is quicker at the start. But the data still has a shape (a schema): it only moves from the database into your application code.

Consistency: ACID and eventual consistency

ACID, which you met in the Transactions & Isolation Levels lesson, is what a transaction promises in an SQL database:

ACID transactions and JOINs across tables are an SQL database's core features. That's why e-commerce with financial transactions uses SQL: money lost halfway through is not acceptable.

Many NoSQL databases choose the BASE model (Basically Available, Soft state, Eventually consistent). In this model, data is copied to several servers called nodes. Eventual consistency means that after new data is written, every node holds the same data only after a while, not right away. In this table, Siti writes through node A, and Budi reads through node B:

time node A node B
10:00:00.000 Siti writes the 101st like still 100
10:00:00.050 101 Budi reads: 100
10:00:00.300 101 101, now the same

For a like count, being a fraction of a second late is fine. For a bank balance, it's a big problem.

Choosing by access pattern

This table lists the choices:

Your need Pick
ACID, transactions, complex relationships, e-commerce, banking SQL
a flexible schema, data whose shape varies NoSQL (document)
horizontal scaling: adding servers rather than growing one NoSQL
real-time and caching: live counters, sessions, caches NoSQL (key-value like Redis)

An SQL database usually grows vertically, meaning it moves to a bigger server, plus replicas (copies of the database on other servers) to serve reads. Many NoSQL databases are built to grow horizontally: the data is split over many servers (sharding). Real apps often use both (polyglot persistence): Sunset Coffee keeps orders in PostgreSQL and caches and sessions in Redis. If you are not sure, start with SQL.

In real projects, two rows of that table (a flexible schema and horizontal scaling) have a third answer. The exercise still uses the answers from the table above.

⚠️ Choosing by hype, not by access pattern

TL;DR: SQL stores every fact once in tables that point at each other by id. It is strong at JOINs, reports across the data (reports that read a lot of data at once), and ACID transactions (Atomicity, Consistency, Isolation, Durability), so it's used for e-commerce and money. NoSQL (document, key-value, graph) gives a flexible schema, fast reads of one whole thing, and horizontal scaling (adding servers rather than growing one). The downside: data is copied to many places, and there is often eventual consistency. That means every node (a server that holds a copy of the data) agrees only after a while, not right away. When Budi changes his name, SQL changes 1 row, while documents change one document for each of his orders. Choose by access pattern (the questions and changes your app sends to the database most often), not hype: ACID, transactions, complex relationships and e-commerce go to SQL; a flexible schema, horizontal scaling, real-time and caching go to NoSQL; often you use both.

⚡ The access pattern decides

Meaning: SQL stores every fact once in tables that point at each other by id. NoSQL (document, key-value, graph) stores data in other shapes, for example one whole document per order. There's no "best": what decides is the questions and changes your app sends to the database most often (the access pattern).

⚡ Budi changes his name

Write:

UPDATE customers SET name = 'Budi Santoso' WHERE id = 1;
Guess first: Budi has 40 orders. In the document model, each order keeps a copy of its buyer's name. How many changes in SQL, and how many in the document model?

SQL needs 1 row in customers. With documents, the name is copied into every order, so updateMany (the MongoDB command that changes many documents) has to change 40 documents.

Meaning: Fetching one whole order is easier with documents. SQL makes it easier to change data that many orders use, such as the buyer's name, and to run reports that read a lot of data at once.

⚡ ACID or eventual consistency

Meaning: An ACID transaction runs several changes that all succeed or all fail, with four guarantees abbreviated ACID. ACID transactions and JOINs across tables are an SQL database's core features, so e-commerce and money use SQL. Many NoSQL databases choose eventual consistency: data is copied to several servers (nodes), and every node agrees only after a while, not right away.

In the exercise, return the exact text: "SQL" or "NoSQL" (capital N, S, Q, L, lowercase o), and "it depends" for a need that is not on the exercise's list.

What you will learn