Skip to content

15 min read

SQL vs NoSQL: when to use each

In one sentence: NoSQL is a label for the databases that don't store tables or speak SQL: key-value stores like Redis, document databases like MongoDB and others. They win in specific cases, like a cache or sessions; for almost everything else, PostgreSQL, which also stores JSON with JSONB.

What you will learn

  • Explain what the “NoSQL” label groups together and why it isn't a specific technology.
  • Use Redis as a cache that expires, and know what's lost if it's shut down suddenly.
  • Store orders as documents in MongoDB and see what having no schema costs.
  • Store attributes with no fixed shape in a JSONB column in PostgreSQL, and decide when you need another database.

Before you start, read: 09-orm.md

Imagine the first day of the shop’s sale. The home page asks for the product list hundreds of times per second, and each time the same QueryA command written in SQL for a database. Mostly the ones that ask for data (SELECT), whose answer is another table, although the ones that add, change or delete rows are called that too.Go to definition goes to PostgreSQL to get the same answer: four products that haven’t changed since yesterday.

On top of that, Ana wants to sell new things, and each one has its own data: the T-shirt, sizes and color; the mug, its capacity and whether it’s dishwasher safe. One column for every piece of data some product might have?

If you ask on a forum, someone will answer without hesitation: “PostgreSQL doesn’t scale. Switch to NoSQL: Redis and MongoDB.” Here you’ll see what’s behind that word, and how part of this can be solved without leaving PostgreSQL.

The analogy

Think of a corner store. The ledger has one line per sale, always with the same columns: date, product, quantity. The price of each product is on another sheet, the catalog’s: each piece of data, in one place only.

Next to the register there’s a blackboard: “Mug: 3 left.” You read it at a glance, and it’s wiped every night. If someone wipes it by mistake, nothing happens: the truth is in the ledger.

And in a cabinet, a folder per customer, with a photocopy of each receipt: product, price and quantity. You open one and you have it all. But if a product changes its name, you have to correct it in every folder.

The ledger is a relational database, the blackboard is Redis and the folders are MongoDB.

Where the analogy breaks down

  • The blackboard isn’t always wiped: Redis can copy its data to disk, as you’ll see.
  • The ledger isn’t slow: with an Index (database)A separate, sorted list with the values of one or more columns of a table and where each row is. With it, the database finds a few rows without reading the whole table. In exchange, it takes up disk space and every write has to update it.Go to definition, PostgreSQL finds one row among millions in milliseconds.
  • MongoDB can cross folders, and PostgreSQL can keep folders in a column: the borders aren’t that clear.

NoSQLA label for the databases that don’t store data in related tables or use SQL for queries, such as key-value stores and document databases. It isn’t one specific technology but a group of them, and each one works its own way and fits different cases.Go to definition groups together the databases that don’t store data in related tables and aren’t queried with SQLSQL stands for Structured Query Language.The language for asking a database to read, add, change or delete the data in its tables. It reads almost like an English sentence, such as SELECT name FROM products, and it says what data you want, not how to find it.Go to definition. The name became popular in 2009, as the title of a meetup, and was later read as “not only SQL.” It says what they aren’t, not what they are:

Family How it stores data Examples What it’s chosen for
Key-value Each value with a name Redis, Valkey Caches, sessions, counters
Documents JSON-like documents, each one complete MongoDB Data with a varying shape that’s read whole
Wide columns Rows spread across many machines Cassandra, ScyllaDB Writing a huge amount, nonstop
Graphs Nodes and the relationships between them Neo4j Networks: your friends’ friends

Many give up the Join (combining tables)The part of an SQL query that puts together the rows of two tables that match on a condition, such as each order with its product. If a row matches several in the other table, it comes out once for each one.Go to definition or TransactionA group of SQL commands that the database treats as one: either all of them are saved, or none. It starts with BEGIN and ends with COMMIT, which saves it, or with ROLLBACK, which undoes all of it.Go to definition to be faster or to spread across machines. But the border has blurred: MongoDB has transactions, and PostgreSQL stores documents.

So the useful question isn’t “SQL or NoSQL?” but what shape your data has and how you’re going to read it.

Redis stores each piece of data with a name

Section titled “Redis stores each piece of data with a name”

Redis is a Key-value storeA database that stores each piece of data under a name, its key, and gives it back when you give it that name, like a dictionary. It doesn’t search by conditions or combine data, and in exchange it’s very fast. Redis is the best known, and it’s widely used as a cache.Go to definition: it stores each value with a name, its key, like a dictionary. You use it from redis-cli, its terminal, like psql with PostgreSQL. This is how the API stores the product list:

The product list, in Redis

Ventana de terminal
redis-cli

What you will see:

127.0.0.1:6379> SET shop:products '[{"id":1,"name":"T-shirt","priceCents":2000},{"id":2,"name":"Mug","priceCents":850},{"id":3,"name":"Hoodie","priceCents":3500},{"id":4,"name":"Cap","priceCents":1500}]'
OK
127.0.0.1:6379> GET shop:products
"[{\"id\":1,\"name\":\"T-shirt\",\"priceCents\":2000},{\"id\":2,\"name\":\"Mug\",\"priceCents\":850},{\"id\":3,\"name\":\"Hoodie\",\"priceCents\":3500},{\"id\":4,\"name\":\"Cap\",\"priceCents\":1500}]"
127.0.0.1:6379> EXPIRE shop:products 60
(integer) 1
127.0.0.1:6379> TTL shop:products
(integer) 60
127.0.0.1:6379> TTL shop:products
(integer) 40
127.0.0.1:6379> TTL shop:products
(integer) -2
127.0.0.1:6379> GET shop:products
(nil)

Each command goes after the >. Between the 60 and the 40, 20 seconds went by, and before the -2, another 41. How to open redis-cli is in Try it. The outputs are from Redis 8.10.

Word by word:

  • SET key value stores the value with that name. shop:products is the key (the : is a convention for grouping names). The value is the API’s JSONJSON stands for JavaScript Object Notation.A format for writing data as text, with braces, quotes and colons: {"product":"mug","quantity":2}. People can read it, and so can almost any programming language, and it’s the most common format for the data that travels between a frontend and a backend.Go to definition, as text: Redis doesn’t look inside.
  • GET key returns the value. The \" are the text’s quotation marks, written that way by redis-cli.
  • EXPIRE key 60 gives it an expiry: in 60 seconds, Redis deletes it. (integer) 1 means “done.”
  • TTL key says how many seconds it has left. -2 means it no longer exists; -1, that it exists and doesn’t expire.
  • (nil) is “there’s nothing with that name.”

Usually you do both in one go: SET shop:products '…' EX 60.

Redis keeps everything in the computer’s memory, not on disk, and answers in much less than a millisecond. In exchange, you ask it by name: there’s no WHERE and no JOIN.

With Redis, the product list becomes a CacheA saved copy of an answer, so it doesn’t have to be fetched again. It saves time, at the cost of the copy possibly being stale until it expires.Go to definition: the API looks in Redis first and, if it isn’t there, asks PostgreSQL and leaves a copy there that expires.

  1. Browser → The shop's APIGET /v2/products
  2. The shop's API → RedisGET shop:products
  3. Redis → The shop's API(nil), not there
  4. The shop's API → PostgreSQLSELECT the products
  5. PostgreSQL → The shop's API4 rows
  6. The shop's API → RedisSET shop:products ... EX 60
  7. The shop's API → Browser200, the list
  8. Browser → The shop's APIGET /v2/products (another customer)
  9. The shop's API → RedisGET shop:products
  10. Redis → The shop's APIthe list
  11. The shop's API → Browser200, without asking PostgreSQL

During that minute, everything comes from Redis: PostgreSQL runs one query per minute instead of thousands.

The price is that of any cache, as with HTTP caching: if Ana changes a price, the API may give the old one for 60 seconds. To avoid that, the API deletes the key when a product changes (DEL shop:products). That’s Cache invalidationMaking sure the saved copies of something that has changed stop being used. It’s hard because the server can’t notify the browsers that already have a copy; it only answers when asked. That’s why short expiration times are used, or the file gets a new name.Go to definition, and you’ll build it in Phase 9.

If Redis dies suddenly, it loses the latest writes

Section titled “If Redis dies suddenly, it loses the latest writes”

What’s in memory dies with the program. A Session (on a website)What a server remembers about a visitor from one request to the next, such as who they are or what’s in their cart. The server keeps that data under a long, random identifier, and the browser only keeps that identifier, almost always in a cookie.Go to definition in Redis, and a power outage (docker kill, like the kill -9 from Phase 1):

Redis, shut down suddenly

Ventana de terminal
docker exec -it redis redis-cli SET session:7f3a9c ana EX 3600
docker exec -it redis redis-cli GET session:7f3a9c
docker kill redis
docker start redis
docker exec -it redis redis-cli GET session:7f3a9c

What you will see:

OK
"ana"
redis
redis
(nil)

Ana’s session is gone: she’d have to log in again. redis is the container from Try it (Docker is Phase 7). If you get "ana", Redis already had a copy with the session on disk: repeat with a new container (docker rm -f redis and the docker run from Try it).

By default, Redis copies its data to disk every so often (every hour if something has changed, sooner if a lot has changed) and when it’s shut down in an orderly way: with docker restart redis, the session is still there. A power outage loses what was written since the last copy. You can tune it:

  • The copies (RDB): more often, or none at all.
  • The change log (AOF): with appendonly yes, Redis writes down every change in a file and saves it every second. A power outage loses one second at most.

In a cache, losing everything doesn’t matter: it’s refilled from PostgreSQL. Losing the sessions makes people log in again. Orders: never only in Redis.

MongoDB is a Document databaseA database that stores each thing (an order, a user) as a document that looks like JSON, with data inside data, without requiring every document to have the same fields. MongoDB is the best known.Go to definition: each order is a JSON-like document, with the product inside. Its terminal is mongosh:

Two orders, in MongoDB

Ventana de terminal
mongosh --quiet

What you will see:

test> use shop
switched to db shop
shop> db.orders.insertOne({ product: { id: 2, name: "Mug", priceCents: 850 }, quantity: 2, status: "pending" })
{
acknowledged: true,
insertedId: ObjectId('6acec23c83346fa9c8bab291')
}
shop> db.orders.insertOne({ product: { id: 2, name: "Mug", priceCents: 850 }, quantty: 3, status: "paid", gift: true })
{
acknowledged: true,
insertedId: ObjectId('6acec23c83346fa9c8bab292')
}
shop> db.orders.find()
[
{
_id: ObjectId('6acec23c83346fa9c8bab291'),
product: { id: 2, name: 'Mug', priceCents: 850 },
quantity: 2,
status: 'pending'
},
{
_id: ObjectId('6acec23c83346fa9c8bab292'),
product: { id: 2, name: 'Mug', priceCents: 850 },
quantty: 3,
status: 'paid',
gift: true
}
]
shop> db.orders.countDocuments({ quantity: { $gte: 1 } })
1

--quiet removes the welcome message. The outputs are from MongoDB 9.0 and mongosh 2.12. Your ObjectId values will be different: they carry the time they were created.

Word by word:

  • use shop chooses the shop database, which is created automatically when you store something.
  • db.orders is the orders collection: the equivalent of a TableWhere a database stores one kind of thing, such as products. Each row is one of those things and each column a piece of data they all have, with its type (a number, some text, a date). It looks like a spreadsheet, but it doesn’t accept data of the wrong type.Go to definition, but without columns.
  • insertOne({ … }) stores a document, with the product inside: its name and its price, copied. Reading an order is a single read, with no JOIN. MongoDB fills in _id.
  • find() returns all the documents.
  • countDocuments({ quantity: { $gte: 1 } }) counts the ones whose quantity is greater than or equal to 1 ($gte, greater than or equal).

Look at the second order: a new field, gift, and a typo, quantty. MongoDB stores both without complaining: it has no fixed Database schemaThe description of a database’s tables: which columns each one has, of what type and what rules they follow. In SQL it’s written with CREATE TABLE.Go to definition. And the count says 1: when you search by quantity, that order doesn’t exist. PostgreSQL would have stopped it at the door:

ERROR: column "quantty" of relation "orders" does not exist
LINE 1: INSERT INTO orders (product_id, quantty, status, created_at)...
^

Just because the database doesn’t check the shape doesn’t mean your data has none. It costs three things.

The schema moves into your code. Every program that writes has to validate the fields, as with Zod in Phase 3. MongoDB can validate documents if you ask it to ($jsonSchema), but by default it doesn’t.

The copies are kept up to date by hand. The mug’s name is copied into every order. If the shop changes it, every copy has to change:

The mug changes its name

Ventana de terminal
db.orders.updateMany({ "product.id": 2 }, { $set: { "product.name": "Ceramic mug" } })

What you will see:

{
acknowledged: true,
insertedId: null,
matchedCount: 2,
modifiedCount: 2,
upsertedCount: 0
}

In the same mongosh session. updateMany changes the documents that match the filter, those for product 2. $set says which field to change, and "product.name" goes into the document inside. Two copies; with a million orders, a million.

In PostgreSQL, the name is in a single row, and the orders read it with a JOIN (lesson 2). UPDATE products SET name = 'Ceramic mug' WHERE id = 2; answers UPDATE 1, however many orders there are. It’s “each piece of data in one place only,” the NormalizationSplitting the data into tables so that each piece of data is stored in only one place, such as a product’s price in its row and not copied into every order. That way, a change is made once and the database can’t contradict itself.Go to definition from lesson 4.

Copying isn’t always a mistake: the price should be copied into the order, because it’s what the customer paid (denormalizing). What you have to decide is what gets copied and who keeps the copies up to date.

There’s no JOIN by default. “The orders with their product’s category” needs $lookup, MongoDB’s JOIN, inside aggregate; or two queries; or copying the category too.

Back to the T-shirt’s sizes and the mug’s capacity. PostgreSQL has a column type for that:

ALTER TABLE products ADD COLUMN attributes jsonb;
UPDATE products SET attributes = '{"color": "black", "sizes": ["S", "M", "L"]}'
WHERE name = 'T-shirt';
UPDATE products SET attributes = '{"dishwasher_safe": true, "capacity_ml": 350}'
WHERE name = 'Mug';
SELECT id, name, attributes FROM products ORDER BY id;
id | name | attributes
----+---------+-----------------------------------------------
1 | T-shirt | {"color": "black", "sizes": ["S", "M", "L"]}
2 | Mug | {"capacity_ml": 350, "dishwasher_safe": true}
3 | Hoodie |
4 | Cap |
(4 rows)
  • ADD COLUMN attributes jsonb adds a column of type jsonb (in PostgreSQL)A PostgreSQL column type that stores a whole JSON document in each row, already broken down into a binary format so you can search inside it. It’s for data that doesn’t always have the same shape, without leaving your usual database. It’s often written JSONB.Go to definition: each row can store a different JSON document. The other rows get NULL, the blanks for the Hoodie and the Cap.
  • In the Mug, the keys have changed order: JSONB doesn’t store the text you wrote, it breaks it down so it can search inside.
  • PostgreSQL checks that it’s valid JSON ('{"color": black}' gives invalid input syntax for type json), but not its shape.

To read inside, two arrows:

SELECT attributes -> 'color' AS json, attributes ->> 'color' AS text,
attributes -> 'sizes' AS sizes
FROM products WHERE name = 'T-shirt';
json | text | sizes
---------+-------+-----------------
"black" | black | ["S", "M", "L"]
(1 row)
  • -> takes out a field as JSON: "black", with its quotation marks, or the list of sizes.
  • ->> takes it out as text: black. It’s the one you use to compare it with text.

And to search, @>, “contains”:

SELECT name FROM products WHERE attributes @> '{"dishwasher_safe": true}';
name
------
Mug
(1 row)

@> returns the rows whose JSON contains that piece. With four products, PostgreSQL looks at them all; with a million, you’d create an index of a special kind, GIN, that notes down every key and every value in the JSON:

CREATE INDEX products_attributes_idx ON products USING GIN (attributes);

What always has the same shape (the name, the price) stays in columns, with their types and ConstraintA rule the database checks on every change, such as the price being greater than zero or no two categories having the same name. Data that breaks it doesn’t get in, wherever it comes from.Go to definition. JSONB is for what varies from one row to another.

PostgreSQL by default, and when the others win

Section titled “PostgreSQL by default, and when the others win”

Almost every application has data that’s related (customers, orders, payments) and needs transactions (lesson 8). PostgreSQL gives you that, and documents with JSONB. And every extra database is one more program to install, monitor and back up. Start with PostgreSQL and add another when a specific problem calls for it:

Situation What to use Why
An answer that’s requested thousands of times and can be a few seconds late Redis, in front of PostgreSQL Memory and expiry
Sessions, one-time codes, requests per minute from each client Redis Small data that expires on its own
A huge number of writes, nonstop, like the messages in a chat Wide columns, like Cassandra or ScyllaDB They spread the writes across many machines
Documents with no fixed shape, read whole and rarely combined with other data MongoDB, or JSONB if everything else is already in PostgreSQL Each document decides its shape
Customers, orders, payments, stock PostgreSQL Relationships, transactions and constraints

A real case: Discord stored its messages in MongoDB, moved to Cassandra as it grew and, later, to ScyllaDB, by then with trillions of messages. Almost no website reaches that scale.

Vector databases, which search by similarity of meaning, come in Phase 11, and there too PostgreSQL has its extension: pgvector.

The goal: give the products attributes with no fixed shape, find the ones that are dishwasher safe and, after that, the black ones. At the end, if you want, Redis and MongoDB on your computer.

Press “Run”: you’ll see the answer to each command.

playground · PostgreSQL in your browser

A real PostgreSQL, with the shop’s data. What you change stays on this page.

Ctrl + Enter runs it too.

If you run it twice, the first command fails: column "attributes" of relation "products" already exists. Press “Reset data”, or delete the first line.

Challenge: give the Hoodie the color black and the sizes M, L and XL, and find all the black products.Show answer

One more UPDATE, and @> with the color:

UPDATE products SET attributes = '{"color": "black", "sizes": ["M", "L", "XL"]}'
WHERE name = 'Hoodie';
SELECT name FROM products WHERE attributes @> '{"color": "black"}';
name
---------
T-shirt
Hoodie
(2 rows)

If you tried WHERE attributes -> 'color' = 'black' and got invalid input syntax for type json, change the arrow: WHERE attributes ->> 'color' = 'black' also finds both.

The same in psql, without changing your database

Section titled “The same in psql, without changing your database”

Your shop database is the project’s, and its schema only changes with MigrationA file with a change to a database’s tables, such as adding a column, that is applied only once and in order, without deleting the data already there. The database itself records in a table which ones have already been applied.Go to definition (lesson 6). So the test goes in a transaction that you undo at the end with ROLLBACK. Open psql -d shop and type:

JSONB in psql, undone at the end

Ventana de terminal
BEGIN;
ALTER TABLE products ADD COLUMN attributes jsonb;
UPDATE products SET attributes = '{"color": "black", "sizes": ["S", "M", "L"]}'
WHERE name = 'T-shirt';
UPDATE products SET attributes = '{"dishwasher_safe": true, "capacity_ml": 350}'
WHERE name = 'Mug';
SELECT name, attributes ->> 'color' AS color, attributes -> 'sizes' AS sizes
FROM products ORDER BY id;
SELECT name FROM products WHERE attributes @> '{"dishwasher_safe": true}';
CREATE INDEX products_attributes_idx ON products USING GIN (attributes);
ROLLBACK;

What you will see:

BEGIN
ALTER TABLE
UPDATE 1
UPDATE 1
name | color | sizes
---------+-------+-----------------
T-shirt | black | ["S", "M", "L"]
Mug | |
Hoodie | |
Cap | |
(4 rows)
name
------
Mug
(1 row)
CREATE INDEX
ROLLBACK

psql leaves blank what the playground writes as NULL. With the ROLLBACK, the column, the attributes and the index disappear: check it with \d products. The outputs are from PostgreSQL 18.6. If you get UPDATE 2, you have two products with that name (you probably created them with the API): no problem. If you get current transaction is aborted, an earlier command failed: type ROLLBACK; and start again.

Redis and MongoDB on your computer (optional)

Section titled “Redis and MongoDB on your computer (optional)”

You don’t need them to follow the course. To repeat this lesson’s outputs, the cleanest way is Docker (Phase 7): each one lives in its own container and is deleted with one command.

Redis and MongoDB, with Docker

Ventana de terminal
docker run -d --name redis redis:8
docker exec -it redis redis-cli PING
docker run -d --name mongo mongo:9
docker exec -it mongo mongosh --quiet --eval 'db.version()'

What you will see:

ba405caf36a7f871c776d3f3ba66d1393ca71d44d6598f0e77e4a273f95b0a00
PONG
2a97dc5f435b3d743bb97f40462351d55081cd599f02e0a1e29bde7741516b17
9.0.2

docker run -d starts the container and prints its number, which will be different for you; the first time, it downloads the image first. PONG is Redis’s answer to PING: it’s alive. To get in, docker exec -it redis redis-cli and docker exec -it mongo mongosh --quiet. When you’re done, docker rm -f redis mongo deletes them along with their data.

Without Docker, you can install them:

  • On macOS, with Homebrew: brew install redis and brew services start redis; MongoDB, with brew tap mongodb/brew, brew install mongodb-community and brew services start mongodb-community.
  • On Ubuntu and WSL: sudo apt install redis-server (Redis 7 on Ubuntu 24.04: these commands work the same). MongoDB isn’t in Ubuntu’s catalog: its manual explains how to add its repository.
  • A website that asks you to log in again after a while without using it: your session has expired. Many websites store them like this, in a key-value store.
  • The browser’s localStorage is a key-value store: you can see it in DevTools (how to open it), Application tab.
  • The idempotency keys from Phase 4, which Stripe can delete after 24 hours: a typical job for Redis.
  • Choosing MongoDB “so you don’t have a schema.” The schema ends up scattered across the code.
  • Keeping in Redis the only copy of something that can’t be lost, like the orders.
  • A cache with no expiry, and no deleting the key when the data changes: old prices for hours.
  • Putting in JSONB what always has the same shape, like the price: you lose the types and the constraints.
  • Adding a database “just in case.” Each one has to be installed, monitored and backed up.
  • NoSQL is a label for the databases without related tables or SQL: key-value, documents, wide columns and graphs.
  • Redis stores each value with a name, in memory, with an expiry (EXPIRE, TTL): a cache or sessions. If it dies suddenly, it loses what was written since its last copy on disk.
  • MongoDB stores complete documents with no fixed schema: reading an order is one read, but typos get in, copies are changed by hand and there’s no JOIN by default.
  • JSONB stores JSON inside PostgreSQL: -> takes out JSON, ->> takes out text, @> searches for what it contains, and a GIN index speeds it up.
  • PostgreSQL is the default choice. Another database is added when a specific problem calls for it.
The API stores the product list in Redis with EX 60. Ana raises the mug’s price in PostgreSQL and, for a while, the website keeps showing the old price. Why?

A server keeps the product cache and the users’ sessions in Redis, with the default configuration. The power goes out. What happens when it comes back?

In MongoDB, someone saves an order with the field quantty instead of quantity. What happens?

The shop is going to sell books (author, pages) and sneakers (size, material), on top of what it already has. Where do you store that data?

You write SELECT name FROM products WHERE attributes -> 'color' = 'black'; and PostgreSQL answers invalid input syntax for type json. What’s going on?

You’re starting a new online shop: customers, products, orders and payments. Someone on the team suggests a database. Which one do you choose to start with?

phase-5 · lesson 10/10