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

Practice Assignment: SQL JOINs vs MongoDB Referencing

๐Ÿงช Practice Assignment: SQL JOINs vs MongoDB Referencing


Here's a clear and practical assignment to help readers compare SQL JOINs with MongoDB referencing. This exercise is designed to reinforce how both systems manage relationships through hands-on tasks.


๐ŸŽฏ Objective:

Understand how to build and query related data using:

  • SQL with JOINs

  • MongoDB with manual referencing


๐Ÿ“š Scenario:

You’re building a simple Library System with:

  • A list of Authors

  • A list of Books written by those authors

Each book belongs to one author, and each author can write multiple books (One-to-Many relationship).


๐Ÿ”น Part A: SQL – Using Foreign Keys & JOINs


Step 1: Create Tables

CREATE TABLE Authors (
  AuthorID INT PRIMARY KEY,
  Name VARCHAR(100)
);

CREATE TABLE Books (
  BookID INT PRIMARY KEY,
  Title VARCHAR(150),
  AuthorID INT,
  FOREIGN KEY (AuthorID) REFERENCES Authors(AuthorID)
);

Step 2: Insert Data

INSERT INTO Authors (AuthorID, Name) VALUES
(1, 'George Orwell'),
(2, 'J.K. Rowling');

INSERT INTO Books (BookID, Title, AuthorID) VALUES
(101, '1984', 1),
(102, 'Animal Farm', 1),
(103, 'Harry Potter', 2);

Step 3: Write a JOIN Query

Write a SQL query to display all book titles along with their author names.

Example:

SELECT Books.Title, Authors.Name
FROM Books
JOIN Authors ON Books.AuthorID = Authors.AuthorID;

๐Ÿ”น Part B: MongoDB – Manual Referencing


Step 1: Insert Documents

Authors Collection:

db.authors.insertMany([
  { _id: 1, name: "George Orwell" },
  { _id: 2, name: "J.K. Rowling" }
]);

Books Collection:

db.books.insertMany([
  { title: "1984", author_id: 1 },
  { title: "Animal Farm", author_id: 1 },
  { title: "Harry Potter", author_id: 2 }
]);

Step 2: Query to Simulate a JOIN

Write MongoDB queries to show book titles and their author names:

Step 1: Get author document

const author = db.authors.findOne({ name: "George Orwell" });

Step 2: Find all books by that author

db.books.find({ author_id: author._id });

๐Ÿ”ธ Optional Challenge: Try Embedding in MongoDB

Instead of referencing, restructure books with embedded author info:

db.books.insertOne({
  title: "1984",
  author: {
    id: 1,
    name: "George Orwell"
  }
});

Then query:

db.books.find({ "author.name": "George Orwell" });

๐Ÿง  Reflection Questions

  1. Which method (JOIN or referencing) felt more intuitive to you?

  2. How does MongoDB referencing differ from SQL JOINs?

  3. What trade-offs do you notice in terms of query performance or complexity?


  • Click Next to view solution with expected outputs


Feel free to share your thoughts in the comments!


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

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

Popular Posts