Showing posts with label DBMS Tutorial. Show all posts
Showing posts with label DBMS Tutorial. Show all posts

SQL ACID Transactions vs NoSQL Consistency Explained for Beginners

๐Ÿ”ท Part 10: Transactions and Consistency in SQL vs NoSQL


๐Ÿ“ Introduction

Ever wondered what happens if a system crashes in the middle of updating data?

That’s where transactions and consistency come in.

  • In SQL, transactions follow ACID rules to keep data safe.

  • In NoSQL, the focus shifts to eventual or tunable consistency, especially in distributed environments.

Let’s explore how both systems keep your data reliable — even during failures.


๐Ÿ”ธ 1. What is a Transaction?

A transaction is a group of operations performed as a single unit of work. Either all succeed, or none happen.

๐Ÿ’ก Example:

Transferring money between accounts:

  • Debit from one account

  • Credit to another
    Both must succeed or be rolled back.


๐Ÿ”น 2. SQL Transactions & ACID Properties

SQL databases (MySQL, PostgreSQL, etc.) support ACID transactions:

Property Description
A – Atomicity All operations complete, or none do
C – Consistency Data moves from one valid state to another
I – Isolation Concurrent transactions don’t interfere
D – Durability Once committed, changes are permanent

✅ SQL Example: Bank Transfer

START TRANSACTION;

UPDATE Accounts SET balance = balance - 500 WHERE account_id = 1;
UPDATE Accounts SET balance = balance + 500 WHERE account_id = 2;

COMMIT;

If something fails, use:

ROLLBACK;

๐Ÿ“Œ Ensures either both updates succeed, or none.


๐Ÿ”น 3. NoSQL Transactions and Consistency

Many NoSQL databases like MongoDB, Cassandra, or DynamoDB prioritize speed and availability, often relaxing strict consistency.

✅ MongoDB Transactions

MongoDB (since v4.0) supports multi-document ACID transactions — similar to SQL.

⚠️ Note: MongoDB transactions require a replica set or sharded cluster, even for local development. If you're using a standalone MongoDB instance, transactions won't work.

const session = db.getMongo().startSession();
session.startTransaction();

try {
  db.accounts.updateOne({ _id: 1 }, { $inc: { balance: -500 } }, { session });
  db.accounts.updateOne({ _id: 2 }, { $inc: { balance: 500 } }, { session });

  session.commitTransaction();
} catch (e) {
  session.abortTransaction();
}

๐Ÿ“ฆ Eventual vs Strong Consistency

Model Description
Strong Consistency Always reads latest write (like SQL)
Eventual Consistency Reads may return stale data temporarily
Tunable Consistency Adjustable based on latency, consistency, etc.

Example: In Cassandra, you can choose consistency level per query (QUORUM, ONE, ALL).

This is called tunable consistency. It lets you adjust the trade-off between consistency, latency, and availability.

  • ONE: Fastest, but may return stale data.
  • QUORUM: Balanced – waits for responses from a majority of replicas.
  • ALL: Strongest – waits for all replicas to respond, but slowest.

Choose based on your app's tolerance for stale data vs need for speed.


๐Ÿง  Comparison Table: SQL vs NoSQL Transactions

Feature SQL (Relational DBs) NoSQL (MongoDB, Cassandra, etc.)
Transactions Built-in ACID Varies by DB (Mongo supports it)
Consistency Model Strong Eventual or Tunable
Rollbacks Yes Some support (Mongo, DynamoDB)
Performance Slower but safer Faster, more scalable

๐Ÿ“ Summary

  • SQL ensures strong consistency using ACID rules.

  • NoSQL offers flexibility, often sacrificing consistency for speed and scale.

  • Some NoSQL databases (like MongoDB, DynamoDB) now support full or partial transactions.


✅ What’s Next?

In Part 11, we’ll explore Database Security Basics — covering user roles, authentication, encryption, and common best practices in both SQL and NoSQL systems.



  • click next forpractice task for transactions

SQL Joins vs NoSQL Referencing: Understanding Data Relationships Easily

๐Ÿ”ท Part 9: Relationships in SQL vs Referencing in NoSQL


This is a key concept that helps readers understand how to link data across tables (SQL) or documents (NoSQL), which is essential for real-world applications like e-commerce, school systems, or social networks.


๐Ÿ“ Introduction

Most databases store related data: customers and orders, students and classes, or products and reviews.

  • In SQL, we use foreign keys and JOINs to link tables.

  • In NoSQL (like MongoDB), we use manual referencing or embedding to connect documents.

Understanding these relationship methods is essential for building scalable and maintainable database designs.


๐Ÿ”ธ 1. Relationships in SQL (Using Joins)

SQL supports:

  • One-to-One

  • One-to-Many

  • Many-to-Many
    …through foreign keys and JOINs.


✅ Example: Students and Classes (One-to-Many)


๐Ÿ“ Tables:

CREATE TABLE Students (
  StudentID INT PRIMARY KEY,
  Name VARCHAR(100)
);

CREATE TABLE Classes (
  ClassID INT PRIMARY KEY,
  StudentID INT,
  Subject VARCHAR(50),
  FOREIGN KEY (StudentID) REFERENCES Students(StudentID)
);

๐Ÿ” Fetching Related Data:

SELECT Students.Name, Classes.Subject
FROM Students
JOIN Classes ON Students.StudentID = Classes.StudentID;

➡️ This JOIN connects each student to their class records.


๐Ÿ”น 2. Relationships in MongoDB (Referencing)

In NoSQL, there are two ways to handle related data:

✅ A. Manual Referencing (Normalized approach)

// students collection
{
  _id: ObjectId("stu101"),
  name: "Aisha Khan"
}

// classes collection
{
  student_id: ObjectId("stu101"),
  subject: "Math"
}

To retrieve, you need two queries:

const student = db.students.findOne({ name: "Aisha Khan" });
const classes = db.classes.find({ student_id: student._id });

✅ B. Embedding (Denormalized approach)

{
  name: "Aisha Khan",
  classes: [
    { subject: "Math" },
    { subject: "Science" }
  ]
}

➡️ This is faster for reads, but harder to update if the same class is shared across students.


๐Ÿ”„ Comparison Table: SQL Joins vs NoSQL Referencing


Feature SQL (Joins) MongoDB (Referencing/Embedding)
Relationship type Foreign keys & JOINs Manual references or embedded documents
Querying Single JOIN query Multiple queries or nested documents
Read performance May be slower due to joins Fast if embedded
Update complexity Centralized & simple More complex with embedded structures
Data duplication Minimal Possible with embedding

๐Ÿง  Best Practices


✅ Use SQL when:

  • Data relationships are complex and frequently queried together

  • You want strong referential integrity

✅ Use NoSQL referencing when:

  • You need flexibility or horizontal scaling

  • Data isn’t always accessed together


๐Ÿ“Œ Quick Summary

  • SQL uses foreign keys and JOINs for linking tables.
  • NoSQL uses manual referencing or embedding to relate documents.
  • Joins are powerful but may affect performance in large datasets.
  • Embedding is fast but risks data duplication and update complexity.


✅ What’s Next?

In Part 10, we’ll dive into Transactions and Consistency — how SQL ensures ACID compliance, and how NoSQL handles consistency across distributed systems.


    Click Next for:
  •  practice assignment comparing SQL JOINs and MongoDB referencing

Featured Post

Hands-On SQL & MongoDB Transaction Practice Task

๐Ÿงช Practice Task: Managing a Simple Fund Transfer System Practical  hands-on practice task  for  transactions and consistency , designed fo...

Popular Posts