9.2 Relational vs NoSQL Databases
Table of Contents
Why This Comparison Matters
When you build a backend, almost every feature eventually needs to store and read data. Choosing how to store that data is one of your most important decisions.
You will hear two big families mentioned all the time:
- Relational databases (often called SQL databases)
- NoSQL databases
They are not rivals where one is “better” in every way. Each is designed around different ideas and trade‑offs. In this chapter you will:
- Understand the core ideas behind relational and NoSQL databases
- See typical use cases for each
- Learn how to think about which one to use
- Read many concrete examples of data modeling in both styles
You will learn individual technologies like PostgreSQL and Redis in later chapters. Here we focus only on the conceptual comparison.
What Are Relational Databases?
Relational databases store data in tables and use relations between those tables.
A table is like a spreadsheet:
| id | name | |
|---|---|---|
| 1 | Alice Doe | alice@example.com |
| 2 | Bob Roe | bob@example.com |
Each row is a record, each column is a field, and each table describes one type of thing. Relations connect tables, for example "this order belongs to this user."
Relational databases are sometimes called SQL databases, because you usually talk to them with SQL, the Structured Query Language.
Typical relational systems: PostgreSQL, MySQL, MariaDB, SQL Server, Oracle Database.
Key Ideas in Relational Databases
Structured schema
Relational databases require a schema: a predefined structure of your tables.
Example schema for a simple shop:
users table
| column | type | description |
|---|---|---|
| id | integer | primary key |
| text | unique, not null | |
| password | text | hashed password |
orders table
| column | type | description |
|---|---|---|
| id | integer | primary key |
| user_id | integer | foreign key to users.id |
| total_cents | integer | order total in cents |
If you try to insert an order with user_id = 999 and there is no user with id = 999, the database will reject it if you defined a foreign key.
This strictness helps keep your data consistent.
Relationships
Relational databases are built around relationships:
- One user can have many orders
- One order can have many items
- One product can belong to many categories
These are represented by keys and join tables. You will learn the details in the rest of the Databases and SQL chapters. Here, remember:
Relational databases are optimized for data with clear structure and well defined relationships.
ACID guarantees
Relational databases usually provide ACID properties for transactions:
- Atomicity, all or nothing
- Consistency, rules are always respected
- Isolation, concurrent operations do not conflict incorrectly
- Durability, once committed, data survives crashes
You do not need to memorize ACID now, you will see it in a separate chapter. Here it is enough to know that relational databases are very good at reliable multi step operations such as:
- Transfer money: subtract from one account and add to another
- Place an order: create order, create order items, update stock
What Are NoSQL Databases?
"NoSQL" is an umbrella term for databases that do not primarily use the traditional relational model with SQL.
Different NoSQL databases look very different. Common types:
| Type | Example systems | Main idea |
|---|---|---|
| Document store | MongoDB, CouchDB | Store flexible JSON-like documents |
| Key value store | Redis, Riak | Store values accessible by a simple key |
| Wide column store | Cassandra, HBase | Tables with flexible columns for huge scale |
| Graph database | Neo4j, ArangoDB | Focus on relationships as a graph |
So "NoSQL" does not mean one single technology. It means "not the classic SQL relational model."
Common traits many NoSQL systems share:
- More flexible schemas
- Often designed for horizontal scaling across many servers
- Sometimes give up some ACID guarantees to get extreme performance or availability
Key Ideas in NoSQL Databases
Flexible or schema-less data
Most NoSQL databases let you store documents with different fields in the same collection.
Example in a document database:
Collection: products
{
"id": 1,
"name": "Simple T-Shirt",
"price": 19.99,
"sizes": ["S", "M", "L"]
}and another document:
{
"id": 2,
"name": "Laptop",
"price": 1299.00,
"specs": {
"cpu": "i7",
"ram_gb": 16
},
"warranty_years": 2
}
Both are products, but they do not have the same fields. That is fine in many NoSQL databases. In a relational database, you would usually design the schema to handle all product fields ahead of time, or create multiple tables.
This flexibility is powerful, but it also means you must manage consistency yourself in your application code.
Data as documents or aggregates
In many NoSQL systems you often store all data that you need together in a single document, instead of splitting it across many tables.
For example, an order document in a document database could look like:
{
"id": 123,
"user": {
"id": 5,
"email": "alice@example.com"
},
"items": [
{"product_id": 10, "name": "Mouse", "price": 15.99, "quantity": 1},
{"product_id": 11, "name": "Keyboard", "price": 39.99, "quantity": 1}
],
"total": 55.98
}Everything about the order is embedded inside one document. You can load the whole order with one query, without joins.
Different priorities than SQL databases
Many NoSQL databases aim for at least some of these:
- Easier horizontal scaling across many machines
- High write throughput
- High availability even when some nodes fail
- Eventual consistency instead of strict immediate consistency
Not all NoSQL systems do all of these, but they often trade some relational features to make large scale problems easier.
Modeling Data: Relational vs NoSQL
To understand the differences better, let us look at very concrete examples.
Example 1: Blog with posts and comments
You are building a blog. Each post has many comments. You want to list a post with its comments.
Relational modeling
You might have:
posts table
| id | title | body |
|---|---|---|
| 1 | Hello world | ... |
comments table
| id | post_id | author | text |
|---|---|---|---|
| 1 | 1 | Alice | Nice post! |
| 2 | 1 | Bob | I agree |
post_idincommentsis a foreign key toposts.id- To fetch a post and comments, you might run:
SELECT * FROM posts WHERE id = 1;
SELECT * FROM comments WHERE post_id = 1;or a join:
SELECT p.id, p.title, c.author, c.text
FROM posts p
LEFT JOIN comments c ON c.post_id = p.id
WHERE p.id = 1;Relationships are normalized, each concept has its own table.
NoSQL modeling (document database)
You might have a single posts collection. Each document has its comments embedded.
{
"id": 1,
"title": "Hello world",
"body": "...",
"comments": [
{"author": "Alice", "text": "Nice post!"},
{"author": "Bob", "text": "I agree"}
]
}To load a post and comments you do one query for that document.
Trade offs:
- Relational
- Easier to search all comments by a specific user, because comments are in their own table.
- Good for very large numbers of comments or when comments are reused.
- Document style
- Very easy to load a post with its comments.
- Good when comments only matter together with the post, and the number of comments is not too extreme.
Example 2: User profiles that change over time
You have users with basic info, and over time you add new profile fields such as "Twitter handle", "favorite color", etc.
Relational approach
You usually update the schema:
- Start with:
CREATE TABLE users (
id SERIAL PRIMARY KEY,
email TEXT NOT NULL,
password TEXT NOT NULL
);- Later add columns:
ALTER TABLE users ADD COLUMN twitter_handle TEXT;
ALTER TABLE users ADD COLUMN favorite_color TEXT;If you suddenly add many optional fields, your table might become wide but still structured.
NoSQL document approach
You just start storing new fields when they appear. No migration required.
Before:
{
"id": 1,
"email": "alice@example.com",
"password": "..."
}After:
{
"id": 1,
"email": "alice@example.com",
"password": "...",
"twitter_handle": "@alice",
"favorite_color": "blue"
}Old documents without these fields still exist. Your code must handle missing fields.
Trade offs:
- Relational:
- More work when you change the schema, but the structure is always explicit.
- NoSQL:
- Easy to add fields, but you must be careful in code when reading older documents.
When Relational Databases Shine
Relational databases are usually a great default choice. They shine when:
1. Your data has strong structure and relationships
Use a relational database when:
- You have clear entities such as Users, Orders, Products, Payments
- There are many relationships such as "user has many orders" or "product belongs to category"
- You need to enforce consistency, such as "every order must belong to an existing user"
Example: E commerce system
- Users, products, categories, orders, order items, stock levels
- You frequently join data, such as listing all orders with user info and product details
Relational databases are designed for this.
2. You need strong consistency
Banking, billing, inventory or any domain where mistakes are expensive.
Example:
- Transfer $100 from account A to account B
- You must never end up in a state where money disappeared or appeared from nowhere
Relational databases, with ACID transactions, make this much easier.
3. You need powerful ad hoc queries
Relational databases are very strong when you often need new queries that were not planned.
Example:
- "Show me all users who ordered more than 3 items last month and spent more than 200 dollars"
- "Show me the top 10 products in each category by revenue"
SQL is very expressive for these questions, and the structure of the data fits the SQL model.
When NoSQL Databases Shine
NoSQL is not "better SQL". It is for different needs.
1. Flexible and evolving data
When your data structure changes often, or each record can look quite different, a document database can be simpler.
Example: User generated content
- Users can add any number of custom fields to their profiles.
- Each product can have different attributes, especially in marketplaces.
In these cases, handling a fixed relational schema can become painful. A document database lets you store what you have without constant migrations.
2. Large scale, high throughput workloads
Some NoSQL systems were built to handle massive scale with many servers.
Example: Logging or analytics events
You collect millions of events per minute, such as:
{
"user_id": 123,
"path": "/products/10",
"duration_ms": 250
}You might choose a system designed for huge write rates and efficient storage of time series or event data.
3. Simple key based access or caching
Key value stores such as Redis are great when:
- You mostly get and set data by a simple key
- Data is often ephemeral or cached
- You need very fast reads and writes in memory
Example:
- Cache user sessions by session id
- Cache the result of an expensive database query
- Store rate limiting counters for each IP address
You typically still use a relational database as the source of truth, and use Redis as a secondary store to speed things up.
4. Graph data
If your domain is naturally a graph, such as:
- Users follow users
- People know people
- Devices connect to devices
then a graph database might be easier to use, because relationships are first class citizens in the model.
Comparing Relational and NoSQL: A Summary Table
| Aspect | Relational (SQL) | NoSQL |
|---|---|---|
| Data model | Tables, rows, columns | Documents, key value, wide column, graph, etc. |
| Schema | Fixed, defined ahead of time | Often flexible or schema less |
| Relationships | First class via foreign keys and joins | Often embedded or handled in application |
| Query language | SQL | Varies, often API specific |
| Transactions & ACID | Strong support | Varies, some limited or different models |
| Best for | Structured, relational data | Flexible, semi structured, large scale scenarios |
| Horizontal scaling | Possible, but more complex | Many systems designed with this in mind |
| Typical uses | E commerce, banking, CRM, traditional apps | Logs, analytics, caching, flexible content, graphs |
You almost never pick "relational vs NoSQL" as an absolute choice for a whole company. It is common to use both, each where it fits best.
Thinking About Trade Offs
When choosing how to store data in a new backend, ask yourself some questions.
How stable is the data structure?
- If you know your entities and relationships are stable, relational is often easier.
- If fields change frequently or each record can be very different, a document database might be better.
How important is strict consistency?
- Money, inventory, permissions usually require strong consistency. Relational databases fit well.
- Logs, metrics, temporary caches can tolerate eventual consistency. NoSQL can work very well here.
Do you need many complex queries?
- If you expect many ad hoc reports and joins, SQL is powerful.
- If you mostly read by key or simple filters and rarely join, NoSQL can be enough.
How big and how fast?
Scaling is a complex topic. Many relational databases scale very far, especially with good indexes and hardware. NoSQL systems can scale horizontally more easily in some scenarios, but they often add complexity somewhere else.
Practical Patterns in Real Backends
In real backend systems, you rarely use only one storage technology for everything.
Common patterns:
- Relational as the main system of record, NoSQL as helper
- PostgreSQL for core business data
- Redis as cache and for sessions
- Maybe a document store for some flexible content
- Event data vs core data
- Relational database for orders, users, etc.
- NoSQL or time series database for huge volumes of analytics events
Example architecture for an e commerce backend:
| Data type | Suggested storage |
|---|---|
| Users, products | Relational database (PostgreSQL) |
| Orders, payments | Relational database with transactions |
| Inventory snapshots | Relational or specialized store |
| User sessions | Redis (key value store) |
| Page view events | NoSQL or log oriented database |
| Cache of product pages | Redis cache |
You will learn how to integrate these pieces in later chapters, including PostgreSQL, Redis, caching, and background processing.
How To Practice This Knowledge
You do not need to become an expert in all types right now. As a beginner backend developer:
- Start with relational databases
- Learn tables, relationships, and SQL.
- Practice modeling a small application, such as a to do list or simple blog.
- Then explore NoSQL for specific problems
- Use Redis to cache some expensive SQL queries.
- Try storing some flexible JSON documents in a document database and compare the experience.
- Compare designs intentionally
For a simple feature like "user posts with comments": - Design it as relational tables.
- Design it as a document model.
- Write down what feels easier for each type of query.
By doing this a few times, you will develop intuition for when relational or NoSQL approaches fit best.
Views: 9
KAHIBARO