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

SQL Joins in SQL Server – INNER, LEFT, RIGHT, FULL Explained with Examples

Part 8: SQL Joins – INNER, LEFT, RIGHT, FULL Explained

Microsoft SQL Server Tutorial Series: Beginner to Expert


Welcome to the Intermediate section of our SQL Server Tutorial Series! In this part, we’ll dive into one of the most important topics in SQL — Joins.

Joins are essential when working with relational databases, as they allow you to combine data from multiple tables based on related columns.


๐Ÿ” What You'll Learn

  • What SQL Joins are and why they matter
  • The difference between INNER, LEFT, RIGHT, and FULL Joins
  • Syntax and visual examples of each type
  • Best practices for using Joins in SQL Server

๐Ÿ“˜ What is a SQL Join?

A SQL Join is used to combine rows from two or more tables, based on a related column between them — often a foreign key and primary key relationship.

Let’s say you have two tables:

Students
---------
StudentID | Name

Enrollments
--------------
EnrollmentID | StudentID | CourseName

To get a list of student names with their courses, you'll use a join on the StudentID column.


๐Ÿ”— Types of Joins in SQL Server

Here are the four main types of joins in SQL Server:
Join Type Description
INNER JOIN Returns only the matching rows between both tables.
LEFT JOIN Returns all rows from the left table, and matched rows from the right table.
RIGHT JOIN Returns all rows from the right table, and matched rows from the left table.
FULL JOIN Returns all rows when there is a match in either table.

๐Ÿง  Example Tables

Let’s assume the following data:
Students
+-----------+---------+
| StudentID | Name    |
+-----------+---------+
| 1         | Alice   |
| 2         | Bob     |
| 3         | Charlie |
+-----------+---------+

Enrollments
+--------------+-----------+---------------+
| EnrollmentID | StudentID | CourseName    |
+--------------+-----------+---------------+
| 1            | 1         | Math          |
| 2            | 2         | Science       |
| 3            | 4         | History       |
+--------------+-----------+---------------+

๐Ÿ”ธ INNER JOIN

SELECT Students.Name, Enrollments.CourseName
FROM Students
INNER JOIN Enrollments
ON Students.StudentID = Enrollments.StudentID;
✅ Returns: Only rows where StudentID matches in both tables.

๐Ÿ”ธ LEFT JOIN

SELECT Students.Name, Enrollments.CourseName
FROM Students
LEFT JOIN Enrollments
ON Students.StudentID = Enrollments.StudentID;
✅ Returns: All students, even if they are not enrolled in any course.

๐Ÿ”ธ RIGHT JOIN

SELECT Students.Name, Enrollments.CourseName
FROM Students
RIGHT JOIN Enrollments
ON Students.StudentID = Enrollments.StudentID;
✅ Returns: All enrollments, even if the student is not found in the Students table.

๐Ÿ”ธ FULL OUTER JOIN


SELECT Students.Name, Enrollments.CourseName
FROM Students
FULL OUTER JOIN Enrollments
ON Students.StudentID = Enrollments.StudentID;
✅ Returns: All students and all enrollments, matching where possible.

๐Ÿ“Š Visual Summary of Join Behavior

Join Type Includes Unmatched Rows From
INNER JOIN None
LEFT JOIN Left Table (Students)
RIGHT JOIN Right Table (Enrollments)
FULL OUTER JOIN Both Tables

๐Ÿ› ️ Best Practices for Using Joins

  • Always use ON clause correctly to prevent Cartesian products.
  • Use INNER JOIN when you only want matched records.
  • Use LEFT JOIN when you want all data from the first (left) table.
  • Make sure joined columns have proper indexes for performance.
  • Use table aliases (S, E) in complex queries to make them readable.

๐Ÿงพ Quick Join Syntax Cheat Sheet

-- INNER JOIN
SELECT * FROM A
INNER JOIN B ON A.ID = B.A_ID;

-- LEFT JOIN
SELECT * FROM A
LEFT JOIN B ON A.ID = B.A_ID;

-- RIGHT JOIN
SELECT * FROM A
RIGHT JOIN B ON A.ID = B.A_ID;

-- FULL JOIN
SELECT * FROM A
FULL OUTER JOIN B ON A.ID = B.A_ID;

✅ Summary

In this tutorial, you learned:

  • How to use SQL Joins in SQL Server
  • INNER, LEFT, RIGHT, and FULL OUTER joins with syntax and examples
  • How Joins combine data from multiple tables
  • Best practices for writing clean and efficient joins

๐Ÿ”— What’s Next?

Now that you’ve mastered SQL Joins, the next part will teach you how to perform grouping and aggregation using GROUP BY, HAVING, and aggregate functions like COUNT(), SUM(), and AVG().


Have any questions or insights? Leave a comment below — let’s grow together! ๐Ÿš€


Stored Procedures & Triggers in SQLite with Python – Fun Beginner Guide

Stored Procedures and Triggers with SQL: A Simple and Fun Tutorial for Everyone

Welcome back to our exciting SQL adventure! In our previous tutorials, we learned how to manage data with commands like SELECT, JOIN, and transactions in our toy store database. Now, let’s dive into something super cool: stored procedures and triggers. These are like magic spells that make your database smarter by automating tasks and responding to changes. This tutorial is designed to be easy to understand, useful for beginners and experienced users, and covers key aspects of stored procedures and triggers. We’ll use SQLite and Python with our toystore.db database, keeping it fun and simple like casting spells in a magical toy shop!


What are Stored Procedures and Triggers?

Imagine you run a toy store and have a favorite recipe for organizing toys—like always checking stock and updating prices in one go. Instead of writing the same instructions every time, you could save that recipe as a magic spell to use whenever you want. That’s what a stored procedure does—it’s a saved set of SQL commands you can run with one call.

Now, imagine a magic alarm that automatically updates your inventory list whenever a toy is sold. That’s a trigger—it automatically runs specific commands when something happens in your database, like adding or deleting data.

In our toy store, we’ll:

  • Create a stored procedure to process a toy sale.
  • Create a trigger to automatically log sales in a history table.
  • Use SQLite and Python to make it all happen.

Why Learn Stored Procedures and Triggers?

Stored procedures and triggers are awesome because:

  • They’re Time-Savers: They let you reuse and automate tasks, like magic shortcuts.
  • They’re Simple: Once you set them up, they’re easy to use.
  • They’re Powerful: They make your database smarter and more organized.
  • They’re Useful: They’re used in apps, websites, and games to handle repetitive tasks.
  • They’re Fun: It’s like programming your database to do tricks for you!

Let’s explore these magical tools in our toy store!


Getting Started

We’ll use Python with SQLite to run our SQL commands, just like in our previous tutorials. Make sure you have Python installed (download it from python.org if needed). SQLite comes with Python, so no extra setup is required. You can also use DB Browser for SQLite to see your data visually, but we’ll focus on Python code for clarity.

Important Note: SQLite has limited support for stored procedures compared to databases like MySQL or PostgreSQL. It doesn’t natively support stored procedures, but we can simulate them using Python functions that run SQL commands. Triggers, however, are fully supported in SQLite. We’ll show both concepts clearly, using SQLite for triggers and Python to mimic stored procedures.

We’ll work with our toystore.db database, using the Toys table, a Sales table, and a new SaleHistory table to log sales automatically. Here’s the setup code:

import sqlite3

# Connect to the database
conn = sqlite3.connect('toystore.db')
cursor = conn.cursor()

# Create Toys table
cursor.execute('''
    CREATE TABLE IF NOT EXISTS Toys (
        ToyID INTEGER PRIMARY KEY,
        Name TEXT,
        Type TEXT,
        Price REAL,
        Stock INTEGER
    )
''')

# Create Sales table
cursor.execute('''
    CREATE TABLE IF NOT EXISTS Sales (
        SaleID INTEGER PRIMARY KEY,
        ToyID INTEGER,
        Quantity INTEGER,
        TotalPrice REAL,
        FOREIGN KEY (ToyID) REFERENCES Toys(ToyID)
    )
''')

# Create SaleHistory table for triggers
cursor.execute('''
    CREATE TABLE IF NOT EXISTS SaleHistory (
        HistoryID INTEGER PRIMARY KEY,
        SaleID INTEGER,
        ToyName TEXT,
        SaleTime TEXT
    )
''')

# Clear existing data to avoid duplicates
cursor.execute("DELETE FROM Toys")
cursor.execute("DELETE FROM Sales")
cursor.execute("DELETE FROM SaleHistory")

# Add toys
cursor.execute("INSERT INTO Toys (Name, Type, Price, Stock) VALUES ('Robot', 'Action Figure', 30.00, 10)")
cursor.execute("INSERT INTO Toys (Name, Type, Price, Stock) VALUES ('Jigsaw', 'Puzzle', 10.00, 15)")
cursor.execute("INSERT INTO Toys (Name, Type, Price, Stock) VALUES ('Teddy', 'Stuffed Animal', 15.00, 8)")

conn.commit()
conn.close()
print("Toy store database ready for stored procedures and triggers!")

What’s Happening?

  • Toys table: Stores toy details with Stock to track inventory.
  • Sales table: Records sales with ToyID, Quantity, and TotalPrice.
  • SaleHistory table: Logs sales with a timestamp for tracking (used by triggers).
  • We added three toys to start.

Our Toys table looks like this:

ToyIDNameTypePriceStock
1RobotAction Figure30.0010
2JigsawPuzzle10.0015
3TeddyStuffed Animal15.008

What is a Stored Procedure?

A stored procedure is a saved set of SQL commands you can run with one call, like a recipe you store for later. In SQLite, we can’t create stored procedures directly, but we can mimic them with Python functions that run SQL commands.

For example, let’s create a “stored procedure” (Python function) to process a toy sale, which:

  1. Checks if there’s enough stock.
  2. Updates the stock in the Toys table.
  3. Adds a sale record to the Sales table.

Example: Simulating a Stored Procedure

import sqlite3

def process_sale(toy_id, quantity):
    conn = sqlite3.connect('toystore.db')
    cursor = conn.cursor()
    
    try:
        # Start transaction
        cursor.execute("SELECT Stock, Price, Name FROM Toys WHERE ToyID = ?", (toy_id,))
        result = cursor.fetchone()
        if not result:
            raise Exception("Toy not found!")
        stock, price, toy_name = result
        
        if stock < quantity:
            raise Exception(f"Not enough {toy_name} in stock!")
        
        # Update stock
        cursor.execute("UPDATE Toys SET Stock = Stock - ? WHERE ToyID = ?", (quantity, toy_id))
        
        # Add sale
        total_price = quantity * price
        cursor.execute("INSERT INTO Sales (ToyID, Quantity, TotalPrice) VALUES (?, ?, ?)",
                      (toy_id, quantity, total_price))
        
        conn.commit()
        print(f"Sale of {quantity} {toy_name}(s) completed!")
        
        # Show results
        cursor.execute("SELECT * FROM Toys WHERE ToyID = ?", (toy_id,))
        print("Updated Toy:", cursor.fetchone())
        cursor.execute("SELECT * FROM Sales WHERE ToyID = ?", (toy_id,))
        print("Sales:", cursor.fetchall())
    
    except Exception as e:
        conn.rollback()
        print(f"Error: {e}. Sale cancelled!")
    
    conn.close()

# Test the procedure
process_sale(1, 2)  # Sell 2 Robots

Output:

Sale of 2 Robot(s) completed!
Updated Toy: (1, 'Robot', 'Action Figure', 30.0, 8)
Sales: [(1, 1, 2, 60.0)]

What is a Trigger?

A trigger is an automatic action that runs when something happens in a table, like adding, updating, or deleting data. For example, we can create a trigger to log every sale in the SaleHistory table with a timestamp.

Example: Creating a Trigger

import sqlite3
from datetime import datetime

conn = sqlite3.connect('toystore.db')
cursor = conn.cursor()

# Create trigger
cursor.execute('''
    CREATE TRIGGER IF NOT EXISTS log_sale
    AFTER INSERT ON Sales
    FOR EACH ROW
    BEGIN
        INSERT INTO SaleHistory (SaleID, ToyName, SaleTime)
        SELECT NEW.SaleID, Toys.Name, DATETIME('now')
        FROM Toys 
        WHERE Toys.ToyID = NEW.ToyID;
    END;
''')

conn.commit()

# Test the trigger by adding a sale
try:
    cursor.execute("UPDATE Toys SET Stock = Stock - 3 WHERE ToyID = 3")
    cursor.execute("INSERT INTO Sales (ToyID, Quantity, TotalPrice) VALUES (3, 3, 45.00)")
    conn.commit()
    print("Sale of 3 Teddies added!")
    
    # Check SaleHistory
    cursor.execute("SELECT * FROM SaleHistory")
    print("Sale History:", cursor.fetchall())

except:
    conn.rollback()
    print("Sale failed!")

conn.close()

Output (timestamp will vary):

Sale of 3 Teddies added!
Sale History: [(1, 3, 'Teddy', '2025-09-03 00:15:23')]

Combining Stored Procedures and Triggers

process_sale(2, 2)  # Sell 2 Jigsaws

# Check SaleHistory
conn = sqlite3.connect('toystore.db')
cursor = conn.cursor()
cursor.execute("SELECT * FROM SaleHistory")
print("Sale History:", cursor.fetchall())
conn.close()

Output:

Sale of 2 Jigsaw(s) completed!
Updated Toy: (2, 'Jigsaw', 'Puzzle', 10.0, 13)
Sales: [(2, 2, 2, 20.0)]
Sale History: [(1, 3, 'Teddy', '2025-09-03 00:15:23'), (2, 2, 'Jigsaw', '2025-09-03 00:15:25')]

Tips for Success

  1. Start Simple: Try one trigger or procedure at a time.
  2. Test Triggers: Insert data to see if your trigger works.
  3. Use Transactions: Combine with transactions for safety.
  4. Check SQLite Limits: SQLite doesn’t support stored procedures natively, so use Python functions.
  5. Practice: Try triggers for logging updates or procedures for complex tasks like discounts.

Recap: Why Learn Stored Procedures and Triggers?

These tools are like magic for your database:

  • They Save Time: Reuse code and automate tasks.
  • They’re Safe: Triggers ensure actions happen consistently.
  • They’re Useful: Used in apps, stores, and games.
  • They’re Fun: It’s like programming your database to be smart!

Common Questions

1. Does SQLite support stored procedures?

Not natively, but Python functions can mimic them.

2. Do triggers work in other databases?

Yes, MySQL, PostgreSQL, and others support triggers and stored procedures with similar syntax.

3. Can triggers cause errors?

Yes, if not written carefully, so test them with small data first.

4. Can I have multiple triggers?

Yes, but each must have a unique name.


๐Ÿงฉ Challenge for Readers

Ready to test your SQL wizardry? Try this challenge:

๐ŸŽฏ Challenge:
Create your own trigger that updates a LowStockAlerts table whenever a toy's stock drops below 5.

Steps:

  1. Create a new table called LowStockAlerts with columns for ToyID, Name, and AlertTime.
  2. Write a trigger that runs AFTER an update to the Toys table’s Stock column.
  3. If Stock < 5, insert a new row into LowStockAlerts with the toy name and the current time.

๐Ÿ’ก Bonus: Combine this with your existing Python “stored procedure” so stock updates from sales automatically trigger the alert!


Wrapping Up

Stored procedures and triggers are like magic spells that make your database smarter and safer. In this tutorial, we used a Python function to simulate a stored procedure for toy sales and created a trigger to log sales automatically in our toystore.db database. Whether you’re a 6th grader or a pro coder, these tools are fun and powerful for automating database tasks.

Try creating your own database for a game or library and experiment with triggers or procedures. Use DB Browser for SQLite to see your data or keep coding in Python. With stored procedures and triggers, you’re now a database wizard, ready to automate your data like a superhero!

Happy SQL adventures, and keep casting those database spells!


๐Ÿš€ What’s Next?

Loved this tutorial? Want to keep leveling up your SQL and Python skills?

  • ๐Ÿ”„ Try building a small inventory or game database from scratch using what you’ve learned.
  • ๐Ÿ’ฌ Share your version of the “Low Stock Alert” challenge in the comments below!
  • ๐Ÿ“ง Subscribe or follow for more fun, beginner-friendly tutorials using real code and creative examples.
  • ๐Ÿง™‍♂️ Keep casting those SQL spells and automating your data like a true database wizard!


Transactions and Rollbacks in SQL: Beginner-Friendly SQLite & Python Tutorial

Transactions and Rollbacks with SQL: A Simple and Fun Tutorial for Everyone

Welcome back to our magical SQL journey! In our previous tutorials, we learned how to manage data in a database using commands like INSERT, SELECT, and JOIN, and we connected tables in our toy store database. Now, let’s explore a super important concept: transactions and rollbacks. These are like a safety net for your database, ensuring your changes are saved only when you’re sure everything is perfect. We’ll use SQLite and Python with our toystore.db database, keeping it fun and simple like organizing a toy store with a magical undo button!


What are Transactions and Rollbacks?

Imagine you’re building a toy castle with blocks. You carefully add blocks one by one, but if one step goes wrong (like a block falls), you want to undo everything and start over to keep the castle perfect. In a database, a transaction is like a group of changes (like adding or updating data) that you want to happen all at once—or not at all. A rollback is like your undo button, letting you cancel those changes if something goes wrong.

For example, in our toy store, if a customer buys two toys, you need to update the toy inventory and record the sale. A transaction ensures both steps happen together, or neither happens if there’s a mistake. This keeps your database safe and accurate!


Why Learn Transactions and Rollbacks?

  • They’re Safe: They protect your data from mistakes, like saving only half a sale.
  • They’re Simple: Just a few commands make your database super reliable.
  • They’re Useful: They’re used in apps, websites, and games to ensure data stays correct.
  • They’re Fun: It’s like having a magic undo button for your database!
  • They Build on SQL: If you know INSERT or UPDATE from our earlier tutorials, you’re ready to learn this.

Let’s dive into our toy store and learn how to use transactions and rollbacks!


Getting Started

We’ll use Python with SQLite to run our SQL commands, just like before. Make sure you have Python installed (download it from python.org if needed). SQLite comes with Python, so no extra setup is required. You can also use DB Browser for SQLite to see your data visually, but we’ll focus on Python code for clarity.

We’ll work with our toystore.db database, using the Toys table and a new Sales table to track toy purchases. Here’s the setup code to create these tables and add some sample data:

import sqlite3

# Connect to the database
conn = sqlite3.connect('toystore.db')
cursor = conn.cursor()

# Create Toys table
cursor.execute('''
    CREATE TABLE IF NOT EXISTS Toys (
        ToyID INTEGER PRIMARY KEY,
        Name TEXT,
        Type TEXT,
        Price REAL,
        Stock INTEGER
    )
''')

# Create Sales table
cursor.execute('''
    CREATE TABLE IF NOT EXISTS Sales (
        SaleID INTEGER PRIMARY KEY,
        ToyID INTEGER,
        Quantity INTEGER,
        TotalPrice REAL,
        FOREIGN KEY (ToyID) REFERENCES Toys(ToyID)
    )
''')

# Clear existing data to avoid duplicates
cursor.execute("DELETE FROM Toys")
cursor.execute("DELETE FROM Sales")

# Add toys
cursor.execute("INSERT INTO Toys (Name, Type, Price, Stock) VALUES ('Robot', 'Action Figure', 30.00, 10)")
cursor.execute("INSERT INTO Toys (Name, Type, Price, Stock) VALUES ('Jigsaw', 'Puzzle', 10.00, 15)")
cursor.execute("INSERT INTO Toys (Name, Type, Price, Stock) VALUES ('Teddy', 'Stuffed Animal', 15.00, 8)")

conn.commit()
conn.close()
print("Toy store database ready for transactions!")

What’s Happening?

  • Toys table: Stores toy details with a new Stock column.
  • Sales table: Records sales with ToyID, Quantity, and TotalPrice.
  • FOREIGN KEY: Ensures data integrity by linking toys to sales.
  • We added 3 toys with different stock levels.

Toys:

ToyIDNameTypePriceStock
1RobotAction Figure30.0010
2JigsawPuzzle10.0015
3TeddyStuffed Animal15.008

What is a Transaction?

A transaction is a group of SQL commands that must all succeed together or not happen at all. It follows the ACID properties:

  • Atomicity: All commands happen as one unit (all or nothing).
  • Consistency: The database stays valid (e.g., stock doesn’t go negative).
  • Isolation: Transactions don’t mess with each other.
  • Durability: Saved changes stay saved, even if the computer crashes.

SQL Transaction Commands

  • BEGIN TRANSACTION: Starts a transaction.
  • COMMIT: Saves all changes.
  • ROLLBACK: Cancels all changes if something fails.

In Python with SQLite, you can use conn.commit() and conn.rollback().


Example 1: A Successful Transaction

import sqlite3

conn = sqlite3.connect('toystore.db')
cursor = conn.cursor()

try:
    cursor.execute("UPDATE Toys SET Stock = Stock - 2 WHERE ToyID = 1")
    cursor.execute("INSERT INTO Sales (ToyID, Quantity, TotalPrice) VALUES (1, 2, 60.00)")
    
    conn.commit()
    print("Sale of 2 Robots completed successfully!")
    
    cursor.execute("SELECT * FROM Toys WHERE ToyID = 1")
    print("Robot Stock:", cursor.fetchone())
    cursor.execute("SELECT * FROM Sales")
    print("Sales:", cursor.fetchall())

except:
    conn.rollback()
    print("Something went wrong, changes undone!")

conn.close()

What’s Happening?

  • try: Handles errors.
  • UPDATE: Reduces Robot stock.
  • INSERT: Adds the sale.
  • commit(): Saves if successful.
  • rollback(): Undoes if an error happens.
Sale of 2 Robots completed successfully!
Robot Stock: (1, 'Robot', 'Action Figure', 30.0, 8)
Sales: [(1, 1, 2, 60.0)]

Example 2: Rolling Back a Failed Transaction

import sqlite3

conn = sqlite3.connect('toystore.db')
cursor = conn.cursor()

try:
    cursor.execute("SELECT Stock FROM Toys WHERE ToyID = 2")
    stock = cursor.fetchone()[0]
    
    if stock < 20:
        raise Exception("Not enough Jigsaws in stock!")
    
    cursor.execute("UPDATE Toys SET Stock = Stock - 20 WHERE ToyID = 2")
    cursor.execute("INSERT INTO Sales (ToyID, Quantity, TotalPrice) VALUES (2, 20, 200.00)")
    
    conn.commit()
    print("Sale completed!")

except Exception as e:
    conn.rollback()
    print(f"Error: {e}. Changes undone!")

cursor.execute("SELECT * FROM Toys WHERE ToyID = 2")
print("Jigsaw Stock:", cursor.fetchone())
cursor.execute("SELECT * FROM Sales WHERE ToyID = 2")
print("Jigsaw Sales:", cursor.fetchall())

conn.close()
Error: Not enough Jigsaws in stock!. Changes undone!
Jigsaw Stock: (2, 'Jigsaw', 'Puzzle', 10.0, 15)
Jigsaw Sales: []

Example 3: Combining Transactions with Joins

First, create a Customers table:

conn = sqlite3.connect('toystore.db')
cursor = conn.cursor()

cursor.execute('''
    CREATE TABLE IF NOT EXISTS Customers (
        CustomerID INTEGER PRIMARY KEY,
        Name TEXT
    )
''')
cursor.execute("DELETE FROM Customers")
cursor.execute("INSERT INTO Customers (Name) VALUES ('Alice')")
conn.commit()
conn.close()

Now process a sale:

import sqlite3

conn = sqlite3.connect('toystore.db')
cursor = conn.cursor()

try:
    cursor.execute("UPDATE Toys SET Stock = Stock - 3 WHERE ToyID = 3")
    cursor.execute("INSERT INTO Sales (ToyID, Quantity, TotalPrice) VALUES (3, 3, 45.00)")
    
    conn.commit()
    print("Sale of 3 Teddies completed!")
    
    cursor.execute('''
        SELECT Customers.Name, Toys.Name, Toys.Stock
        FROM Sales
        INNER JOIN Toys ON Sales.ToyID = Toys.ToyID
        INNER JOIN Customers ON Customers.CustomerID = 1
        WHERE Sales.ToyID = 3
    ''')
    print("Sale Details:", cursor.fetchall())

except:
    conn.rollback()
    print("Sale failed, changes undone!")

conn.close()
Sale of 3 Teddies completed!
Sale Details: [('Alice', 'Teddy', 5)]

Tips for Success

  1. Use Transactions when multiple commands must go together.
  2. Check Conditions like stock before updating.
  3. Test Rollbacks using intentional errors.
  4. Write Clear Code for debugging and maintenance.
  5. Practice with your own mini projects!

Common Questions

1. Are transactions hard?

No! Think of them as grouped commands with undo.

2. Do transactions work in other databases?

Yes! PostgreSQL, MySQL, and others support them.

3. What happens if I forget to commit?

Changes may be lost. Always call commit() explicitly.

4. Can I rollback after commit?

No, you must start a new transaction to reverse a change.


Wrapping Up

Transactions and rollbacks in SQL are like a magical safety net, ensuring your database changes are all-or-nothing. In this tutorial, we used transactions to process toy sales, rolled back a failed sale, and combined transactions with joins in our toystore.db database. Whether you’re a beginner or an experienced coder, transactions are a fun and essential skill for keeping data safe.

Try creating your own database for something cool, like a game or library, and practice transactions. Use DB Browser for SQLite to see your data or keep coding in Python. With transactions and rollbacks, you’re now a database superhero, keeping your data safe and sound!

Happy SQL adventures, and keep your data secure!


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 →

Understanding Primary and Foreign Keys in Databases (With Examples for Beginners)

 

← Back to Home

๐Ÿ”ท Part 4: Primary Keys and Foreign Keys – Building Relationships in Databases


๐Ÿ“ Introduction

So far, we’ve learned how data is stored in tables and how we use SQL to interact with it. But what happens when your database has more than one table?

That’s where relationships come in — and they’re built using keys.

Keys help connect tables, maintain data integrity, and allow complex queries across multiple data sets. Today, we’ll explore Primary Keys and Foreign Keys, the foundation of relational database design.


๐Ÿ”‘ What is a Primary Key?

A Primary Key is a unique identifier for each record in a table. No two rows can have the same primary key, and it can’t be left empty (NULL).

๐Ÿ” Example – Students Table:

| StudentID | Name  | Course     |
|-----------|-------|------------|
| 1         | Aisha | Math       |
| 2         | Ravi  | Science    |
| 3         | Sara  | English    |

Here, StudentID is the Primary Key — each student has a unique ID.

๐Ÿ“˜ Think of it like a roll number in a classroom — no two students have the same roll number.


๐Ÿ”— What is a Foreign Key?

A Foreign Key is a column in one table that refers to the primary key in another table. It creates a link between two related tables.


๐Ÿงฉ Example: Students & Results Tables

๐Ÿงพ Students Table

| StudentID | Name  |
|-----------|-------|
| 1         | Aisha |
| 2         | Ravi  |

๐Ÿงพ Results Table

| ResultID | StudentID | Subject  | Marks |
|----------|-----------|----------|-------|
| 101      | 1         | Math     | 85    |
| 102      | 2         | Science  | 90    |

In this case:

  • StudentID is the Primary Key in the Students table.

  • StudentID in the Results table is a Foreign Key — it refers to the Students table.

๐Ÿ’ก This relationship ensures that every result belongs to a valid student.


๐Ÿ” Why Use Keys and Relationships?

  • Data Integrity: Prevents orphaned or mismatched records

  • Less Redundancy: No need to repeat data across tables

  • Scalability: Makes your database easier to maintain as it grows

  • Real-Life Modeling: Mimics real-world relationships (students have results, customers place orders, etc.)


๐Ÿ”ง SQL Example: Defining Primary and Foreign Keys

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

-- Create Results Table
CREATE TABLE Results (
  ResultID INT PRIMARY KEY,
  StudentID INT,
  Subject VARCHAR(50),
  Marks INT,
  FOREIGN KEY (StudentID) REFERENCES Students(StudentID)
);

๐Ÿ“š Real-Life Analogy

Imagine:

  • Primary Key = National ID Number

  • Foreign Key = Form asking for your National ID

You can’t submit the form unless your ID is valid — just like foreign keys rely on real, matching primary keys.


๐Ÿง  Recap

  • Primary Key: Uniquely identifies a row in a table (e.g., StudentID)

  • Foreign Key: Connects a row to another table using a reference

  • These keys help create relationships between tables and ensure the accuracy and reliability of your data.


✅ What’s Next?

In Part 5, we’ll explore NoSQL databases — a modern alternative to relational databases that works better for unstructured data, large-scale applications, and real-time needs.



Relational Databases for Beginners: Simple Guide with Examples

 

← Back to Home

Part 2: Understanding Relational Databases and Tables


Introduction

In our first post, we learned what a database is and why it is essential in today’s digital world. Now, let us take a closer look at relational databases, the most common type used in everything from websites to banking systems.

Relational databases store data in a structured format using tables — a simple but powerful way to organize and retrieve information efficiently.


๐Ÿ”น What is a Relational Database?

A Relational Database is a type of database that organizes data into tables. Each table consists of rows (records) and columns (fields), and every row is uniquely identified — often by a Primary Key.

This structure is called “relational” because data in different tables can be related through keys.


๐Ÿ”น Tables, Rows, and Columns Explained

Let’s break down the basic components:

Table

A table represents a specific entity — like Students, Products, or Employees.

Row (Record)

Each row represents one item or entry in the table.

Column (Field)

Each column holds a specific type of data, like name, age, or email.


๐Ÿ“Š Example: A Simple Students Table

| StudentID | Name     | Course      | Marks |
|-----------|----------|-------------|-------|
| 1         | Aisha    | Mathematics | 85    |
| 2         | Ravi     | Science     | 90    |
| 3         | Sara     | English     | 78    |
  • StudentID is a Primary Key — a unique value for each student.

  • Name, Course, and Marks are fields that store the student’s information.

๐ŸŽ“ Real-Life Analogy: Think of a table as an Excel sheet — each row is a student, and each column is a category like name or marks.


๐Ÿ”น Why Use Tables?

  • Organization: Easy to categorize and search data

  • Relationships: Link data between multiple tables (e.g., a Students table and a Courses table)

  • Data Integrity: Reduces errors and redundancy

  • Performance: Optimized for quick queries and large datasets


๐Ÿ”— What Makes It “Relational”?

The real power of relational databases comes from their ability to relate data across multiple tables using keys:

  • Primary Key: A unique identifier for a row (like StudentID)

  • Foreign Key: A column in another table that refers to a primary key

We shall explore this more in Part 4: Keys and Relationships in Databases.


๐Ÿง  Quick Recap

  • A Relational Database stores data in structured tables.

  • Each row = a record, and each column = a field.

  • Tables can relate to one another using keys.

  • This format makes querying, updating, and organizing data efficient and reliable.


✅ What’s Next?

In Part 3, we’ll introduce SQL (Structured Query Language) — the language used to interact with relational databases. You’ll learn how to write simple SQL commands to create, read, and update data.



Featured Post

Creating Your First MongoDB Database and Collection (Step-by-Step Tutorial)

Creating Your First MongoDB Database and Collection A Super Fun, Step-by-Step Adventure for Beginner to Expert Level What is MongoDB? ...

Popular Posts