Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"label": "Relational Databases",
"position": 7,
"link": {
"type": "generated-index",
"description": "Learn how to store data in structured tables, use SQL to query information, and understand why RDBMS is the backbone of the banking and enterprise world."
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
---
sidebar_position: 3
title: "ACID Properties: The DNA of RDBMS"
sidebar_label: "3. ACID Properties"
description: "Learn the four essential rules that keep your database safe and reliable."
---

In India, we use apps like **PhonePe, GPay, or Paytm** every single day. Have you ever wondered what happens if your internet cuts out exactly when you are sending ₹500 to a friend?

Does the money vanish? Does it get stuck in the "middle"?

**No.** This is thanks to **ACID Properties**. These are the 4 golden rules that every Relational Database must follow to ensure your data is 100% safe.

## The 4 Pillars of ACID

### 1. Atomicity (The "All or Nothing" Rule)

In a database, a "Transaction" is a series of steps. Atomicity ensures that either **every step** happens, or **none** of them do.

**The Real-World Example:**
Imagine you are transferring ₹500 to your friend Rahul.
1. Bank deducts ₹500 from your account.
2. **Server Crashes!**
3. Bank fails to add ₹500 to Rahul's account.

Because of **Atomicity**, the database will "Rollback." It sees the crash, cancels the first step, and puts the ₹500 back in your account as if nothing ever happened.

### 2. Consistency (The "Follow the Rules" Rule)

Every database has rules (Constraints). Consistency ensures that a transaction never leaves the database in a "weird" state.

**The Real-World Example:**
If your bank has a rule that "Balance cannot be negative," and you try to send ₹1000 when you only have ₹500, the database will block the transaction immediately. The rules stay intact!

### 3. Isolation (The "No Cutting in Line" Rule)

Modern databases handle thousands of users at the same time. Isolation ensures that one person's transaction doesn't "leak" into another's.

**The Real-World Example:**
Imagine there is only **1 last seat** left on a bus from Delhi to Mumbai.
* You and another person click "Book" at the exact same microsecond.
* **Isolation** makes them wait in a digital line. One person gets the seat, and the other gets a "Sold Out" message. They don't both get charged for the same seat!

### 4. Durability (The "Saved Forever" Rule)

Once the database tells you "Transaction Successful," that data is permanent.

**The Real-World Example:**
Even if the bank's data center loses power or a server explodes 1 second after your transaction is finished, your balance will still be correct when the power comes back. The record is written to a permanent disk, not just temporary memory.

## Summary Table

| Property | Short Meaning | "Desi" Analogy |
| :--- | :--- | :--- |
| **A**tomicity | All or Nothing | Like a 'Paisa Vasool' deal—you get everything promised or your money back. |
| **C**onsistency | Data Integrity | No "Jugaad" allowed—the rules are the rules. |
| **I**solation | Separate Work | Mind your own business—don't let others' work mix with yours. |
| **D**urability | Permanent Save | Written in stone—even if the world ends, the record stays. |

## Summary Checklist
* [x] I understand that ACID keeps data safe during crashes.
* [x] I know that "Atomicity" prevents partial updates.
* [x] I understand why "Isolation" is needed for many users.
* [x] I recognize that "Durability" means the data is permanent.

:::tip Career Advice
Interviewers love asking about ACID. If you explain it using the "Bank Transfer" example like we did here, you will show them that you don't just memorize definitions—you actually understand how the real world works!
:::
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
---
sidebar_position: 6
title: "Database Migrations"
sidebar_label: "6. Migrations"
description: "Learn how to track and manage changes to your database schema using version control for data."
---

Have you ever added a new column to a table on your laptop, but then your teammate's code crashed because *their* database didn't have that column?

In the old days, you had to send a `.sql` file to your friend and say, "Hey, run this command." **Database Migrations** solve this problem by automating the process.

## 🧐 What is a Migration?

A **Migration** is a small script (usually in JavaScript, Python, or SQL) that describes a specific change to your database structure.

* **Migration Files** are kept in your GitHub repository.
* When a teammate pulls your code, they run one command, and their database is instantly updated to match yours.

## How Migrations Work: UP and DOWN

Every migration file has two main functions:

1. **UP:** What should happen when we apply the migration? (e.g., Create a table).
2. **DOWN:** How do we "Undo" this change if we made a mistake? (e.g., Drop the table).

<Tabs>
<TabItem value="js" label="💻 Migration Example (JavaScript)" default>

```javascript
// Adding a 'phone_number' column to the Users table
export async function up(knex) {
return knex.schema.table('users', (table) => {
table.string('phone_number').nullable();
});
}

// Undoing the change
export async function down(knex) {
return knex.schema.table('users', (table) => {
table.dropColumn('phone_number');
});
}

```

</TabItem>
<TabItem value="sql" label="🔍 Migration Example (Raw SQL)">

```sql
-- UP: Apply the change
ALTER TABLE Users ADD COLUMN phone_number VARCHAR(15);

-- DOWN: Undo the change
ALTER TABLE Users DROP COLUMN phone_number;

```

</TabItem>
</Tabs>

---

## The Migration Workflow

At **CodeHarborHub**, we follow this industrial workflow to keep our data in sync:

1. **Create:** You generate a new migration file (e.g., `20260313_add_bio_to_users.js`).
2. **Write:** You define the `up` and `down` logic.
3. **Run:** You execute the migration command (e.g., `npx knex migrate:latest`).
4. **Commit:** You push the migration file to **GitHub**.
5. **Sync:** Your teammates pull the code and run the same command. **Boom! Everyone is on the same page.**

```mermaid
sequenceDiagram
participant DevA as Developer A
participant GH as GitHub (Code)
participant DevB as Developer B

DevA->>DevA: Creates Migration Script
DevA->>DevA: Runs 'Migrate' (Local DB updated)
DevA->>GH: Pushes Script to Repo
GH->>DevB: Pulls Code
DevB->>DevB: Runs 'Migrate' (Local DB updated)
Note over DevA,DevB: Both Databases are now identical!

```

---

## Why You Should NEVER Edit Tables Manually

If you go into your database tool (like pgAdmin or MySQL Workbench) and manually add a column:

* **Production will crash:** When you deploy your code, the live server won't have that column.
* **Loss of History:** You won't know *when* or *why* that change was made.
* **Team Friction:** Your teammates will constantly get "Table not found" errors.

## Summary Checklist

* [x] I understand that Migrations are "Version Control" for my database.
* [x] I know that `up` applies changes and `down` reverts them.
* [x] I understand that migration files should be committed to GitHub.
* [x] I promise to never manually edit my database schema in production.

:::tip Career Secret
In a job interview, if you mention that you use **Migrations** to manage your schema instead of manual SQL scripts, you immediately look like a 10x more experienced developer. It shows you know how to work in a **real team**.
:::
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
---
sidebar_position: 7
title: "Indexes & Query Performance"
sidebar_label: "7. Performance"
description: Learn "how to make your database queries lightning fast using Indexes and execution analysis."
---

Imagine you are in a massive library with 1,000,000 books. If you want to find a book about "Node.js," you don't start at the first shelf and check every book. You go to the **Index Catalog** at the front, find the shelf number, and go straight there.

In a database, an **Index** does exactly the same thing.

## What is an Index?

An index is a separate data structure (usually a **B-Tree**) that stores a sorted version of a specific column. This allows the database to "jump" to the data instead of scanning the whole table.

### ✅ Pros:

* **Speed:** Searching becomes 100x to 1000x faster.
* **Efficiency:** Reduces the load on your server's CPU and Memory.

### ❌ Cons:

* **Storage:** Indexes take up extra disk space.
* **Write Speed:** Every time you `INSERT` or `UPDATE`, the database has to update the index too. **Don't index every column!**

## How to Create an Index

<Tabs>
<TabItem value="single" label="☝️ Single Column" default>

If you frequently search for users by their email, add an index to the `email` column.

```sql
CREATE INDEX idx_user_email ON Users(email);
```

</TabItem>
<TabItem value="composite" label="✌️ Composite Index">

If you often search for people using both `first_name` AND `last_name`, a composite index is better.

```sql
CREATE INDEX idx_full_name ON Users(first_name, last_name);

```

</TabItem>
</Tabs>

## Performance Analysis: The `EXPLAIN` Command

How do you know if your query is actually using an index or being slow? You ask the database to explain its "Query Plan."

```sql
EXPLAIN ANALYZE
SELECT * FROM Users WHERE email = 'aryan@codeharborhub.github.io';
```

**What to look for in the output:**

* **Seq Scan (Sequential Scan):** BAD. The DB is reading every row in the table.
* **Index Scan:** GOOD. The DB is using your index to find the data instantly.
* **Cost:** Lower is better!

## Top 3 Performance Tips for Backend Devs

### 1. Avoid `SELECT *`

Only ask for the columns you need.

* `SELECT * FROM Users;` (Heavy and slow)
* `SELECT name, email FROM Users;` (Light and fast)

### 2. Use `LIMIT`

If you have 1 million users, don't fetch them all at once. Use pagination.

```sql
SELECT * FROM Users LIMIT 10 OFFSET 0;
```

### 3. Index your Foreign Keys

Always create an index on columns used in `JOIN` operations. This prevents the database from getting confused when linking large tables.

## Summary Checklist

* [x] I understand that an Index is like a library catalog for my data.
* [x] I know that Indexes speed up **Reads** but slow down **Writes**.
* [x] I can use `EXPLAIN ANALYZE` to check my query performance.
* [x] I know why `SELECT *` is a "Red Flag" in professional code.

:::tip Interview Secret
If a Senior Developer asks you "How do you optimize a slow API?", your first answer should always be: **"I would check the database logs and see if we need to add an Index or optimize the SQL query using EXPLAIN."**
:::

**Congratulations!** You've completed the Relational Database Module.
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
---
sidebar_position: 1
title: "Introduction to RDBMS"
sidebar_label: "1. What is RDBMS?"
description: "The fundamental building blocks of Relational Database Management Systems for beginners."
---

In the world of Backend Development, data is everything. But how do we store it so that it stays organized, secure, and easy to find? We use a **Relational Database Management System (RDBMS)**.

## 🧐 The "Spreadsheet" Analogy

The easiest way to understand a Relational Database is to think of it as a collection of **Excel Spreadsheets** that are linked together.

Imagine you are running a school:
* One sheet for **Students** (Name, Roll No, Age).
* One sheet for **Courses** (Course Name, Teacher).
* One sheet for **Enrollments** (Which Student is in which Course).

Instead of repeating a student's name 10 times, you just link their unique **Roll Number**. That is the "Relationship" in Relational Database!

## Core Components of RDBMS

Every Relational Database is built using these three specific parts:

<Tabs>
<TabItem value="tables" label="📊 Tables" default>
The basic container. Everything in RDBMS is a table.
* **Rows (Records):** Represent a single item (e.g., One specific student).
* **Columns (Fields):** Represent a property (e.g., Student's Email).
</TabItem>
<TabItem value="keys" label="🔑 Keys">
Keys are the "Glue" that holds tables together.
* **Primary Key (PK):** A unique ID that identifies a specific row (e.g., Roll No).
* **Foreign Key (FK):** A link used to refer to a Primary Key in another table.
</TabItem>
<TabItem value="constraints" label="⛓️ Constraints">
Rules that the data must follow.
* **NOT NULL:** This column cannot be empty.
* **UNIQUE:** No two rows can have the same value in this column.
</TabItem>
</Tabs>

## Visualizing the Relationship

Using a **Mermaid Diagram**, we can see how an E-commerce database actually "relates" different tables:

```mermaid
erDiagram
USER ||--o{ ORDER : places
ORDER ||--|{ PRODUCT : contains
USER {
string username
string email PK
string password
}
ORDER {
int order_id PK
string user_email FK
date created_at
}
PRODUCT {
int product_id PK
string name
float price
}

```

## Why do we use RDBMS?

:::tip The Golden Rule
If your data is **structured** (fits into rows and columns) and needs to be **100% accurate** (like a bank balance), use an RDBMS.
:::

1. **Data Integrity:** It ensures that you cannot delete a user if they still have active orders.
2. **Scalability:** Modern RDBMS like PostgreSQL can handle millions of rows without slowing down.
3. **Security:** You can control exactly who can read or write to specific tables.
4. **Standard Language:** Almost every RDBMS uses **SQL**, making your skills transferable.

## ACID: The Security Shield

Relational Databases follow the **ACID** principle to ensure that even if the server crashes, your data remains safe.

:::info Quick Definition

* **Atomicity:** All parts of a transaction succeed, or none do.
* **Consistency:** Data follows all defined rules.
* **Isolation:** Transactions don't interfere with each other.
* **Durability:** Once saved, data stays saved even during power failure.
:::

## Summary Checklist

* [x] I know that RDBMS stands for Relational Database Management System.
* [x] I understand that tables are linked using **Primary** and **Foreign Keys**.
* [x] I recognize that data is stored in Rows and Columns.
* [x] I understand why ACID properties are important for data safety.

:::note Homework
Think about a Social Media app like Instagram. What tables would you need? (Hint: Users, Posts, Comments). Try to imagine which columns would be the "Primary Keys"!
:::
Loading
Loading