KAHIBARO
Discord Login Register

9.2 Relational vs NoSQL Databases

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:

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:

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:

idnameemail
1Alice Doealice@example.com
2Bob Roebob@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

columntypedescription
idintegerprimary key
emailtextunique, not null
passwordtexthashed password

orders table

columntypedescription
idintegerprimary key
user_idintegerforeign key to users.id
total_centsintegerorder 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:

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:

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:

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:

TypeExample systemsMain idea
Document storeMongoDB, CouchDBStore flexible JSON-like documents
Key value storeRedis, RiakStore values accessible by a simple key
Wide column storeCassandra, HBaseTables with flexible columns for huge scale
Graph databaseNeo4j, ArangoDBFocus 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:

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

json
{
  "id": 1,
  "name": "Simple T-Shirt",
  "price": 19.99,
  "sizes": ["S", "M", "L"]
}

and another document:

json
{
  "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:

json
{
  "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:

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

idtitlebody
1Hello world...

comments table

idpost_idauthortext
11AliceNice post!
21BobI agree
sql
SELECT * FROM posts WHERE id = 1;
SELECT * FROM comments WHERE post_id = 1;

or a join:

sql
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.

json
{
  "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:

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:

  1. Start with:
sql
   CREATE TABLE users (
     id SERIAL PRIMARY KEY,
     email TEXT NOT NULL,
     password TEXT NOT NULL
   );
  1. Later add columns:
sql
   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:

json
{
  "id": 1,
  "email": "alice@example.com",
  "password": "..."
}

After:

json
{
  "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:

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:

Example: E commerce system

Relational databases are designed for this.

2. You need strong consistency

Banking, billing, inventory or any domain where mistakes are expensive.

Example:

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:

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

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:

json
{
  "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:

Example:

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:

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

AspectRelational (SQL)NoSQL
Data modelTables, rows, columnsDocuments, key value, wide column, graph, etc.
SchemaFixed, defined ahead of timeOften flexible or schema less
RelationshipsFirst class via foreign keys and joinsOften embedded or handled in application
Query languageSQLVaries, often API specific
Transactions & ACIDStrong supportVaries, some limited or different models
Best forStructured, relational dataFlexible, semi structured, large scale scenarios
Horizontal scalingPossible, but more complexMany systems designed with this in mind
Typical usesE commerce, banking, CRM, traditional appsLogs, 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?

How important is strict consistency?

Do you need many complex queries?

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:

Example architecture for an e commerce backend:

Data typeSuggested storage
Users, productsRelational database (PostgreSQL)
Orders, paymentsRelational database with transactions
Inventory snapshotsRelational or specialized store
User sessionsRedis (key value store)
Page view eventsNoSQL or log oriented database
Cache of product pagesRedis 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:

  1. Start with relational databases
    • Learn tables, relationships, and SQL.
    • Practice modeling a small application, such as a to do list or simple blog.
  2. 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.
  3. 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

Comments

Please login to add a comment.

Don't have an account? Register now!