Showing posts with label Beginner Database Guide. Show all posts
Showing posts with label Beginner Database Guide. Show all posts

Complete Solution: Fund Transfer with Transactions

Here's the complete solution to the Practice Task on Transactions and Consistency, for both SQL and MongoDB, including full code, output, and explanations.


Complete Solution: Fund Transfer with Transactions


๐Ÿ”น Part A: SQL Solution


๐Ÿ“ 1. Table Creation

CREATE TABLE Accounts (
  AccountID INT PRIMARY KEY,
  Name VARCHAR(100),
  Balance DECIMAL(10, 2)
);

๐Ÿ“ฅ 2. Insert Sample Data

INSERT INTO Accounts (AccountID, Name, Balance) VALUES
(1, 'Aisha', 1000.00),
(2, 'Ravi', 500.00);

๐Ÿ” 3. Transaction Script

START TRANSACTION;

-- Step 1: Deduct ₹200 from Aisha
UPDATE Accounts
SET Balance = Balance - 200
WHERE AccountID = 1;

-- Step 2: Add ₹200 to Ravi
UPDATE Accounts
SET Balance = Balance + 200
WHERE AccountID = 2;

-- Final step: Commit the transaction
COMMIT;

๐Ÿ“Œ If an error occurs during either update, you would use:

ROLLBACK;

๐Ÿ“ค Expected Output (after COMMIT):

SELECT * FROM Accounts;
AccountID Name Balance
1 Aisha 800.00
2 Ravi 700.00

✅ Data is consistent and correct. Both updates were applied atomically.


๐Ÿงช Optional Test Failure Scenario

Try this (invalid ID):

START TRANSACTION;

UPDATE Accounts SET Balance = Balance - 200 WHERE AccountID = 1;
UPDATE Accounts SET Balance = Balance + 200 WHERE AccountID = 999; -- wrong ID

ROLLBACK;

๐Ÿ” This would rollback everything. Aisha’s balance remains unchanged.


๐Ÿ”น Part B: MongoDB Solution


๐Ÿ“ฅ 1. Insert Documents

db.accounts.insertMany([
  { _id: 1, name: "Aisha", balance: 1000 },
  { _id: 2, name: "Ravi", balance: 500 }
]);

๐Ÿ” 2. MongoDB Transaction with Session

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

try {
  // Deduct from Aisha
  db.accounts.updateOne(
    { _id: 1 },
    { $inc: { balance: -200 } },
    { session }
  );

  // Add to Ravi
  db.accounts.updateOne(
    { _id: 2 },
    { $inc: { balance: 200 } },
    { session }
  );

  // Commit the transaction
  session.commitTransaction();
  print("✅ Transaction committed.");
} catch (error) {
  session.abortTransaction();
  print("❌ Transaction aborted:", error.message);
} finally {
  session.endSession();
}

๐Ÿ“ค Expected Output After Querying:

db.accounts.find().pretty();
[
  { _id: 1, name: "Aisha", balance: 800 },
  { _id: 2, name: "Ravi", balance: 700 }
]

✅ Like in SQL, both operations succeeded together.


๐Ÿ”ฅ Test Failure Scenario in MongoDB

Simulate a failure by modifying the second update with an invalid field:

db.accounts.updateOne(
  { _id: 999 },
  { $inc: { balance: 200 } },
  { session }
);

➡️ MongoDB will throw an error, and the first update will be rolled back automatically when abortTransaction() is called.


๐Ÿง  Final Thoughts

Operation SQL MongoDB
Begin Transaction START TRANSACTION session.startTransaction()
Commit COMMIT session.commitTransaction()
Rollback ROLLBACK session.abortTransaction()
Atomicity Built-in Requires session/replica set
Use Case High integrity systems (e.g. banks) NoSQL with transactional guarantees (MongoDB 4.0+)

Part 11: Database Security Basics

๐Ÿš€ In the next part of this tutorial series, we’ll shift focus to Database Security Basics. You'll learn about user roles, privileges, authentication, and how to protect your data from unauthorized access—an essential step for any real-world application.


๐Ÿ‘ If you found this tutorial helpful, consider following to the blog or sharing it with a friend or teammate learning databases.


๐Ÿ’ฌ Got questions or a better approach? Drop a comment below—I’d love to hear your thoughts!


๐Ÿ” Ready for more? Check out the next post on Database Security →

NoSQL Databases Explained: Beginner's Guide to Flexible Data Storage (With Examples)


๐Ÿ”ท Part 5: Introduction to NoSQL Databases – A Flexible Alternative to Relational Models


๐Ÿ“ Introduction

So far, we’ve learned how relational databases work with structured tables, rows, and columns. But what if your data doesn’t fit neatly into tables?

Welcome to NoSQL — a more flexible way to store and manage data. Whether you're building apps with real-time feeds, handling massive data from sensors, or creating dynamic content, NoSQL databases offer a powerful solution.


๐Ÿ”น What is NoSQL?

NoSQL stands for “Not Only SQL.”
It refers to a group of databases that store and retrieve data in ways other than traditional tabular formats (used by relational databases).

NoSQL is often used for:

  • Unstructured or semi-structured data

  • High-speed, high-volume applications

  • Scalable systems like social networks, IoT platforms, or real-time analytics


๐Ÿงฐ Types of NoSQL Databases

  1. Document-Based – Stores data as JSON-like documents (e.g., MongoDB)

  2. Key-Value Stores – Stores data as simple key-value pairs (e.g., Redis)

  3. Column-Family Stores – Similar to tables but with flexible columns (e.g., Cassandra)

  4. Graph Databases – Designed to represent complex relationships (e.g., Neo4j)


๐Ÿ” Document-Based NoSQL Example (MongoDB)

Here’s how a student record might look in a NoSQL document store:

{
  "student_id": 1,
  "name": "Aisha",
  "class": "10A",
  "marks": [
    { "subject": "Math", "score": 85 },
    { "subject": "English", "score": 88 }
  ]
}

๐Ÿ”„ Compare this to the relational model where marks are in a separate table. In NoSQL, all related data can be stored together in one document.


๐Ÿ†š NoSQL vs SQL – Key Differences

Feature SQL (Relational) NoSQL (Non-Relational)
Structure Fixed tables and schemas Flexible, schema-less
Data Format Rows and columns JSON, key-value, graphs, etc.
Relationships Supports JOINs Embeds or references data
Scalability Vertical (scale-up) Horizontal (scale-out)
Best For Structured, consistent data Dynamic, varied, big data

๐Ÿ“š Real-Life Analogy

Imagine SQL is like organizing books in a library, where every book must follow a strict format (title, author, ISBN).

NoSQL is like a digital folder, where each file (document) can have different details — one may have a title and summary, another may have a title, author, and image — and that’s perfectly okay.


๐Ÿง  When to Use NoSQL?

Use NoSQL when:

  • Data structure is not fixed

  • You're dealing with lots of rapidly changing data

  • You need fast performance and easy scalability

  • Relationships between data are simple or embedded


๐Ÿง  Recap

  • NoSQL databases offer flexibility and speed for non-tabular data

  • They store data in formats like documents or key-value pairs

  • Great for modern apps, real-time systems, and unstructured data

  • Popular tools: MongoDB, Redis, Cassandra, Firebase


✅ What’s Next?

In Part 6, we’ll perform real-world CRUD operations in both SQL and NoSQL — showing how to Create, Read, Update, and Delete data with easy examples.


Practice Set: MongoDB Document Modeling Practice


Featured Post

GROUP BY, HAVING, and Aggregations in SQL Server Explained

Part 9: GROUP BY, HAVING, and Aggregations in SQL Server Microsoft SQL Server Tutorial Series: Beginner to Expert Welcome to Part 9 of...

Popular Posts