Showing posts with label mysql. Show all posts
Showing posts with label mysql. Show all posts

MySQL Chapter 11 to 17

Chapter 11 — Indexes ⭐⭐⭐

Assume this table:

employees

+--------+--------+---------+
| id     | name   | salary  |
+--------+--------+---------+
| 1      | Rahul  | 50000   |
| 2      | Aman   | 70000   |
| ... 10 Million Rows ...   |

Q1. Suppose your company has 10 million employees, and your manager says:

"Find employee whose id = 8765432."

Answer (Without Index)

SELECT *
FROM employees
WHERE id = 8765432;

Database checks:

Row 1 ❌
Row 2 ❌
Row 3 ❌
...
Row 8765432 ✅

This is called Full Table Scan.

Slow.


Create Index

CREATE INDEX idx_employee_id
ON employees(id);

Now the same query:

SELECT *
FROM employees
WHERE id = 8765432;

Database jumps almost directly to the record.

Fast.

Concepts Covered

  • Index

  • Full Table Scan

  • Faster Searching

  • B-Tree (internally)


Q2. Suppose your manager says:

"Should we create indexes on every column?"

Answer

❌ No.

Bad idea.

CREATE INDEX idx_name ON employees(name);
CREATE INDEX idx_salary ON employees(salary);
CREATE INDEX idx_email ON employees(email);
CREATE INDEX idx_phone ON employees(phone);
...

Problems

  • INSERT becomes slower

  • UPDATE becomes slower

  • DELETE becomes slower

  • More storage required

Indexes speed up reading, but slow down writing.


Q3. Suppose users search employees by both department and salary.

Answer

Instead of

CREATE INDEX idx_department
ON employees(department);

CREATE INDEX idx_salary
ON employees(salary);

Use Composite Index

CREATE INDEX idx_dept_salary
ON employees(department, salary);

Useful query

SELECT *
FROM employees
WHERE department='IT'
AND salary > 50000;

Q4. Suppose the interviewer asks:

"When should we create an index?"

Answer

Create indexes on columns frequently used in

WHERE
JOIN
ORDER BY
GROUP BY

Avoid indexing

  • Small tables

  • Frequently updated columns

  • Columns rarely searched


Chapter 12 — EXPLAIN

Assume

SELECT *
FROM employees
WHERE name='Rahul';

Q1. Suppose your query is taking 8 seconds.

How will you find the reason?

Answer

Use

EXPLAIN

SELECT *
FROM employees
WHERE name='Rahul';

Output (simplified)

type = ALL
rows = 10000000
key = NULL

Meaning

Database scanned every row.


Q2. Suppose after creating an index, you run EXPLAIN again.

Answer

CREATE INDEX idx_name
ON employees(name);

EXPLAIN

SELECT *
FROM employees
WHERE name='Rahul';

Output

type = ref

key = idx_name

rows = 1

Meaning

Database used the index.

Very fast.


Q3. Suppose EXPLAIN shows

key = NULL

What does it mean?

Answer

No index was used.

Possible reasons

  • No index exists

  • Wrong query

  • Function on indexed column

  • Database optimizer chose table scan


Q4. Suppose interviewer asks:

"Why do developers use EXPLAIN?"

Answer

To know

  • Which index is used

  • Which table is scanned

  • Estimated rows

  • Join order

  • Query cost

It helps optimize slow queries.


Chapter 13 — Transactions

Assume Rahul transfers ₹1000 to Priya.

Current Balance

Rahul 5000

Priya 3000

Q1. Suppose money is deducted from Rahul but the server crashes before adding it to Priya.

What should happen?

Answer

Use Transaction.

START TRANSACTION;

UPDATE accounts
SET balance = balance - 1000
WHERE id = 1;

UPDATE accounts
SET balance = balance + 1000
WHERE id = 2;

COMMIT;

Either both succeed

OR

None happen.


Q2. Suppose second query fails.

Answer

START TRANSACTION;

UPDATE accounts
SET balance = balance -1000
WHERE id=1;

-- Error

ROLLBACK;

Output

Rahul still has

5000

Money isn't lost.


Q3. Suppose interviewer asks:

"Difference between COMMIT and ROLLBACK?"

Answer

COMMIT

Save permanently

ROLLBACK

Undo everything since transaction started

Q4. Suppose interviewer asks:

"What are ACID properties?"

Answer

A → Atomicity

Everything or nothing.

C → Consistency

Database remains valid.

I → Isolation

Transactions don't interfere.

D → Durability

Committed data survives crashes.


Chapter 14 — Full Text Search

Assume

articles

id

title

content

Q1. Suppose users search

Machine Learning

Should you use

WHERE title LIKE '%Machine%'

?

Answer

No.

Better

MATCH(title, content)

AGAINST('Machine Learning');

Much faster.

Designed for searching text.


Q2. Suppose users search

AI Engineer

Answer

SELECT *
FROM articles
WHERE MATCH(title,content)
AGAINST('AI Engineer');

Output

Only relevant articles.


Q3. Suppose interviewer asks:

"LIKE vs Full Text Search?"

Answer

LIKE

✔ Simple

✔ Small tables

❌ Slow on large text

Full Text

✔ Fast

✔ Ranking

✔ Natural language search

✔ Millions of rows


Q4. Suppose you want to enable Full Text Search.

Answer

CREATE FULLTEXT INDEX idx_article

ON articles(title,content);

Now

MATCH...

AGAINST...

works efficiently.


Chapter 15 — Pagination

Assume

Products

1 million rows

Q1. Suppose your website displays 20 products per page.

How will you show Page 1?

Answer

SELECT *
FROM products

LIMIT 20;

Output

Rows 1-20

Q2. Suppose user clicks Page 2.

Answer

SELECT *
FROM products

LIMIT 20 OFFSET 20;

Output

Rows 21-40

Q3. Suppose user clicks Page 5.

Answer

SELECT *
FROM products

LIMIT 20 OFFSET 80;

Formula

OFFSET

(page-1) × page_size

Q4. Suppose interviewer asks:

"Why is OFFSET pagination slow?"

Answer

For

OFFSET 900000

Database still skips

900000 rows.

Better approach

Keyset Pagination

SELECT *

FROM products

WHERE id > 500

LIMIT 20;

Much faster.


Chapter 16 — Basic Scaling Concepts


Q1. Suppose 10 lakh users visit your website today.

Database becomes slow.

What will you do first?

Answer

Use Cache.

Instead of

User

↓

Database

Use

User

↓

Cache

↓

Database

Frequently requested data comes from cache.

Database load reduces.

Popular tools

Redis

Memcached

Q2. Suppose thousands of users are only reading data.

Answer

Use Read Replica.

Writes

↓

Primary Database

↓

Replica 1

Replica 2

Replica 3

Read queries go to replicas.

Write queries go to primary.


Q3. Suppose every post shows

Likes = 12,45,678

Should database count likes every time?

Answer

No.

Maintain

likes_count

inside Posts table.

Whenever someone likes

likes_count +=1

This is called

Denormalized Counter

Much faster.


Q4. Suppose interviewer asks:

"Cache vs Replica vs Denormalized Counter"

Answer

ConceptPurpose
CacheAvoid repeated database queries
ReplicaHandle many read requests
Denormalized CounterAvoid expensive COUNT() queries

Chapter 17 — Final Integration (Putting It All Together)

Assume you're building Amazon.


Q1. Suppose customer searches:

"Wireless Mouse"

What database concepts are used?

Answer

Full Text Search
↓

Index

↓

LIMIT 20

SQL

SELECT *
FROM products
WHERE MATCH(name, description)
AGAINST('Wireless Mouse')
LIMIT 20;

Q2. Suppose customer opens page 6 of products.

What concepts are involved?

Answer

SELECT *
FROM products
ORDER BY id
LIMIT 20 OFFSET 100;

Concepts used:

  • ORDER BY

  • LIMIT

  • OFFSET (Pagination)

  • Index on id for faster sorting


Q3. Suppose customer places an order.

What happens?

Answer

START TRANSACTION;

UPDATE products
SET stock = stock - 1
WHERE id = 10;

INSERT INTO orders(...);

UPDATE users
SET total_orders = total_orders + 1
WHERE id = 5;

COMMIT;

Concepts involved:

  • Transaction

  • COMMIT

  • Primary Key

  • Foreign Key

  • Index

  • Atomicity


Q4. Suppose interviewer asks:

"A query is slow in production. What is your step-by-step approach?"

Answer

  1. Run EXPLAIN to inspect the execution plan.

  2. Check whether the query is using an appropriate index.

  3. Add or optimize indexes if necessary.

  4. Rewrite inefficient joins or filters.

  5. Cache frequently requested data.

  6. Use read replicas if the workload is read-heavy.

  7. Replace expensive COUNT() operations with denormalized counters where appropriate.

  8. Re-run EXPLAIN and measure performance again.


🎯 At this point, you've covered the core SQL concepts used in real-world applications:

  • Database Basics

  • Tables & Data Types

  • CRUD

  • WHERE

  • ORDER BY

  • LIMIT

  • Joins

  • GROUP BY

  • Aggregate Functions

  • Primary & Foreign Keys

  • Database Design

  • Indexes

  • EXPLAIN

  • Transactions

  • Full-Text Search

  • Pagination

  • Basic Scaling Concepts

This progression takes you from writing simple queries to understanding how production databases are designed, optimized, and scaled.

MySQL Chapter 6 to 10

Chapter 6 — JOINS

Goal: Learn every type of JOIN and understand when to use it.

Assume we have two tables:

students
+----+--------+----------+
| id | name   | class_id |
+----+--------+----------+
| 1  | Rahul  | 101      |
| 2  | Priya  | 102      |
| 3  | Aman   | 105      |
| 4  | Neha   | NULL     |
+----+--------+----------+
classes
+-----+----------+
| id  | class    |
+-----+----------+
|101  | Physics  |
|102  | Maths    |
|103  | Biology  |
+-----+----------+

Q1. Suppose your manager says:

"Show every student along with their class name."

Answer

Need INNER JOIN

SELECT
    students.name,
    classes.class
FROM students
INNER JOIN classes
ON students.class_id = classes.id;

Output

+--------+----------+
| Rahul  | Physics  |
| Priya  | Maths    |
+--------+----------+

Why?

Only matching records are returned.

Aman isn't shown because class 105 doesn't exist.

Neha isn't shown because class_id is NULL.


Q2. Suppose your manager says:

"Show ALL students. If their class exists, show it; otherwise show NULL."

Answer

Need LEFT JOIN

SELECT
    students.name,
    classes.class
FROM students
LEFT JOIN classes
ON students.class_id = classes.id;

Output

+--------+----------+
| Rahul  | Physics  |
| Priya  | Maths    |
| Aman   | NULL     |
| Neha   | NULL     |
+--------+----------+

Why?

LEFT JOIN always keeps every row from the left table.


Q3. Suppose your manager says:

"Show every class, even if no student belongs to it."

Answer

Need RIGHT JOIN

SELECT
    students.name,
    classes.class
FROM students
RIGHT JOIN classes
ON students.class_id = classes.id;

Output

+--------+----------+
| Rahul  | Physics  |
| Priya  | Maths    |
| NULL   | Biology  |
+--------+----------+

Why?

RIGHT JOIN always keeps every row from the right table.


Q4. Suppose your manager says:

"Explain all JOINs in one example."

Answer

JOINReturns
INNER JOINOnly matching rows
LEFT JOINAll left rows + matching right rows
RIGHT JOINAll right rows + matching left rows
FULL JOIN*Everything from both tables

*MySQL doesn't directly support FULL JOIN.

JOIN Syntax

SELECT columns
FROM table1
JOIN table2
ON table1.column = table2.column;

Concepts Covered ✅

  • INNER JOIN

  • LEFT JOIN

  • RIGHT JOIN

  • FULL JOIN (theory)

  • Matching rows

  • Non-matching rows

  • ON clause

  • NULL after joins

  • Real interview usage


Chapter 7 — GROUP BY

Assume:

orders

+----+----------+--------+
|id  | customer | amount |
+----+----------+--------+
|1   | Rahul    | 200    |
|2   | Rahul    | 100    |
|3   | Priya    | 500    |
|4   | Aman     | 100    |
|5   | Priya    | 300    |
+----+----------+--------+

Q1. Suppose your manager says:

"How many orders did each customer place?"

Answer

SELECT customer,
COUNT(*) AS total_orders
FROM orders
GROUP BY customer;

Output

Rahul   2
Priya   2
Aman    1

Why?

GROUP BY creates groups.

COUNT() counts rows inside each group.


Q2. Suppose your manager says:

"Calculate total money spent by every customer."

Answer

SELECT customer,
SUM(amount) AS total
FROM orders
GROUP BY customer;

Output

Rahul   300
Priya   800
Aman    100

Q3. Suppose your manager says:

"Show customers whose total spending is greater than 500."

Answer

SELECT customer,
SUM(amount) total
FROM orders
GROUP BY customer
HAVING SUM(amount) > 500;

Output

Priya   800

Why HAVING?

WHERE filters before grouping.

HAVING filters after grouping.


Q4. Suppose your manager says:

"What's the difference between WHERE and HAVING?"

Answer

-- Before grouping

WHERE amount > 100

-- After grouping

HAVING SUM(amount) > 500

Concepts Covered ✅

  • GROUP BY

  • Group creation

  • COUNT()

  • SUM()

  • HAVING

  • WHERE vs HAVING

  • Aliases

  • Group-wise calculations


Chapter 8 — Aggregate Functions

Assume:

employees

+------+--------+
|name  |salary  |
+------+--------+
|Rahul |50000   |
|Aman  |70000   |
|Priya |60000   |
|Neha  |90000   |
+------+--------+

Q1. Suppose your manager says:

"What is the highest salary?"

Answer

SELECT MAX(salary)
FROM employees;

Output

90000

Q2. Suppose your manager says:

"What is the minimum salary and average salary?"

Answer

SELECT
MIN(salary),
AVG(salary)
FROM employees;

Output

50000
67500

Q3. Suppose your manager says:

"How much salary does the company pay in total?"

Answer

SELECT SUM(salary)
FROM employees;

Output

270000

Q4. Suppose your manager says:

"How many employees are there?"

Answer

SELECT COUNT(*)
FROM employees;

Output

4

Aggregate Functions Summary

FunctionPurpose
COUNT()Count rows
SUM()Total
AVG()Average
MAX()Largest value
MIN()Smallest value

Concepts Covered ✅

  • COUNT

  • SUM

  • AVG

  • MAX

  • MIN

  • Numeric aggregation

  • Single-row result


Chapter 9 — Primary & Foreign Keys

Assume:

students

+----+-------+
|id  |name   |
+----+-------+
|1   |Rahul  |
|2   |Priya  |
+----+-------+
orders

+----+------------+
|id  |student_id  |
+----+------------+
|1   |1           |
|2   |1           |
|3   |2           |
+----+------------+

Q1. Suppose your manager says:

"Every student must have a unique ID. How will you enforce that?"

Answer

CREATE TABLE students(
    id INT PRIMARY KEY,
    name VARCHAR(50)
);

Why?

Primary Key

  • Unique

  • Cannot be NULL

  • One per table


Q2. Suppose your manager says:

"Orders should only belong to existing students."

Answer

CREATE TABLE orders(
    id INT PRIMARY KEY,
    student_id INT,
    FOREIGN KEY(student_id)
    REFERENCES students(id)
);

Why?

Foreign Key prevents invalid references.

You can't insert:

student_id = 999

if student 999 doesn't exist.


Q3. Suppose someone deletes Rahul.

What happens?

Answer

Depends on the foreign key rule.

ON DELETE CASCADE

Deletes Rahul and all related orders.

ON DELETE SET NULL

Orders remain, but student_id becomes NULL.

ON DELETE RESTRICT

Deletion is blocked if related orders exist.


Q4. Suppose the interviewer asks:

"Difference between Primary Key and Foreign Key?"

Answer

Primary KeyForeign Key
UniqueCan repeat
Not NULLCan be NULL
Identifies a rowReferences another table
One per tableMany allowed

Concepts Covered ✅

  • Primary Key

  • Foreign Key

  • Uniqueness

  • Referential Integrity

  • References

  • Parent table

  • Child table

  • ON DELETE CASCADE

  • ON DELETE SET NULL

  • ON DELETE RESTRICT


Chapter 10 — Database Design

Assume you're building an e-commerce website.


Q1. Suppose your manager says:

"Can we store customer name, address, products, quantity, and payment details all in one table?"

Answer

Technically yes…

orders

id
customer_name
customer_address
product_name
price
quantity
payment_type
payment_status
...

But this is bad design.

Problems:

  • Duplicate customer data

  • Hard to update

  • Wasted storage

  • Inconsistent information

Instead:

Customers

Orders

Products

Payments

Separate tables.


Q2. Suppose a customer changes their address.

What should happen?

Bad Design

Update 1000 rows

Good Design

Update only Customers table.

Orders automatically reference the customer.


Q3. Suppose one order contains five products.

How should you design it?

Answer

Orders

OrderItems

Products
Orders
--------
1

OrderItems
-----------
order_id
product_id
quantity

Never store:

Laptop,Mouse,Keyboard

inside one column.


Q4. Suppose the interviewer asks:

"What are the characteristics of a good database design?"

Answer

A good design should:

  • Avoid duplicate data

  • Use primary keys

  • Use foreign keys

  • Keep related data together

  • Separate unrelated data

  • Be easy to maintain

  • Be scalable

  • Prevent inconsistencies

Concepts Covered ✅

  • Normalization (basic idea)

  • Data duplication

  • One table per entity

  • Relationships

  • One-to-many relationship

  • Order & OrderItems pattern

  • Scalability

  • Maintainability

  • Good schema design principles

MySQL Chapter 10: Primary & Foreign Keys πŸ”‘

Chapter 10: Primary & Foreign Keys πŸ”‘

🎯 Goal

By the end of this chapter, you'll understand:

  • What a Primary Key is

  • Why every table needs a Primary Key

  • What a Foreign Key is

  • Why Foreign Keys exist

  • How tables are connected

  • Parent and Child tables

  • Referential Integrity

  • What happens when keys are missing

  • Real-world examples


Part 1 — The Story (Learn Like a Movie)

🎬 The Kingdom's Giant Library

The kingdom had the world's largest library.

There were:

  • πŸ“š 2 million books

  • πŸ‘¨‍πŸŽ“ 500,000 students

  • πŸ“– 10 million borrow records

Initially...

The librarian stored records like this:

Student NameBook Name
RahulSQL Basics
RahulDatabase Design
PriyaPython
RahulAI for Beginners

Everything looked fine...


One Day...

A new student joined.

His name?

Rahul

Now there were two Rahuls.

The librarian became confused.

Someone asked:

"Which Rahul borrowed 'SQL Basics'?"

Librarian:

🀯

"No idea."


Next Disaster

A student changed his name.

Rahul became:

Rahul Sharma

Now every borrow record had to be updated.

There were 12,000 borrow entries for Rahul.

The librarian spent three days updating records.


Then Another Problem

Someone accidentally typed:

Rahool

instead of

Rahul

Now the system thought:

Rahul

Rahool

Rahul Sharma

were three different people.

Chaos.


Enter the Database Wizard

The wizard said,

"Stop identifying people by their names."

Everyone looked confused.


The wizard gave every student a magical ID.

Student IDName
101Rahul
102Priya
103John
104Rahul

Notice something?

Two Rahuls.

No problem.

Because IDs are unique.


Now borrow records became

Borrow IDStudent IDBook
1101SQL Basics
2104Python
3102Java

Now the king asked:

"Which Rahul borrowed SQL Basics?"

Wizard:

Student ID = 101

Done.


The King Asked

"But how do we know Student ID 101 actually exists?"

Wizard smiled.

"That's where Foreign Keys come in."


He made another rule.

Borrow table:

Borrow IDStudent IDBook
1101SQL Basics

The Student ID must exist in the Students table.

If someone tried:

Borrow IDStudent IDBook
2999Python

Wizard shouted:

"There is no Student 999!"

Database rejected it.


King:

"So Borrow table points to Students table?"

Wizard:

"Exactly."


Another Example

Amazon

Customers

Customer IDName
1Rahul
2Priya

Orders

Order IDCustomer ID
10011
10022
10031

Order doesn't store:

Rahul
Rahul
Rahul
Rahul
Rahul

Instead:

Customer ID = 1

Less storage.

No spelling mistakes.

Faster searching.

Easy updates.


King finally understood.

"Primary Keys identify."

"Foreign Keys connect."

Wizard smiled.

"Exactly."


What Actually Happened?

Every table should have a way to uniquely identify each row.

That unique identifier is called a Primary Key.

Other tables use that value to create relationships.

That reference is called a Foreign Key.


What is a Primary Key?

A Primary Key is a column (or set of columns) whose value uniquely identifies every row in a table.

Example

Students

Student_IDName
1Rahul
2Priya
3John

Here,

Student_ID

is the Primary Key.

Because every value is unique.


Rules of a Primary Key

A Primary Key must:

✅ Be unique

✅ Never be NULL

✅ Identify exactly one row


Wrong Example

ID
1
1
2

❌ Duplicate value.


Wrong Example

ID
1
NULL
2

❌ NULL not allowed.


Creating a Primary Key

CREATE TABLE students (
    student_id INT PRIMARY KEY,
    name VARCHAR(100),
    age INT
);

Now student_id must always be unique.


Real-Life Primary Keys

Hospital

Patient_ID

Bank

Account_Number

Passport Office

Passport_Number

University

Roll_Number

Company

Employee_ID

Why Not Use Name?

Names can:

  • Repeat

  • Change

  • Be misspelled

IDs don't.


What is a Foreign Key?

A Foreign Key is a column that refers to the Primary Key of another table.

It creates a relationship.

Example

Students

Student_IDName
1Rahul
2Priya

Borrow

Borrow_IDStudent_ID
1001
1012

Borrow table doesn't know names.

It only stores Student_ID.


Visualizing the Relationship

Students Table

Student_ID (PK)
      │
      │
      ▼
Borrow Table

Student_ID (FK)

Think of the Foreign Key as a bridge connecting two tables.


Creating a Foreign Key

CREATE TABLE borrow (
    borrow_id INT PRIMARY KEY,
    student_id INT,
    book_name VARCHAR(100),

    FOREIGN KEY (student_id)
    REFERENCES students(student_id)
);

Now every student_id in borrow must exist in students.


Parent Table vs Child Table

Students

Borrow

Students = Parent

Borrow = Child

Because Borrow depends on Students.


Referential Integrity

Big name.

Simple idea.

It means:

Relationships between tables should always remain valid.

Example

Students

Student_ID
1
2

Borrow

Student_ID
1

Valid.


Invalid

Borrow

Student_ID
999

Student 999 doesn't exist.

Database rejects it.

That's referential integrity.


Why Foreign Keys Matter

Imagine Amazon.

Without Foreign Keys:

Orders

OrderCustomer_ID
199999

Customer doesn't exist.

But order exists.

Impossible situation.

Foreign Keys prevent this.


Can One Primary Key Have Many Foreign Keys?

Absolutely.

Customer

Customer_ID
1

Orders

Customer_ID
1

Reviews

Customer_ID
1

Wishlist

Customer_ID
1

One customer can have many related records.


Primary Key vs Foreign Key

Primary KeyForeign Key
Uniquely identifies a row.References another table's Primary Key.
Must be unique.Can repeat.
Cannot be NULL.Can be NULL (unless restricted).
One per table (commonly).A table can have many Foreign Keys.

Common Mistakes

Mistake 1

Using Name as Primary Key

Rahul
Rahul
Rahul

❌ Names aren't guaranteed to be unique.


Mistake 2

Foreign Key without Parent

Orders

Customer_ID = 999

Customer doesn't exist.

Database rejects it (if the constraint exists).


Mistake 3

Changing Primary Key values often

Primary Keys should remain stable.

If IDs keep changing, all related Foreign Keys must also change.


Real-Life Examples

YouTube

Users

User_ID

Videos

User_ID

Foreign Key connects the video to its uploader.


Instagram

Users

Posts

Comments

Likes

Everything is connected using keys.


Banking

Customers

Accounts

Transactions

Each transaction belongs to an account, and each account belongs to a customer.


Hospital

Patients

Appointments

Prescriptions

Bills

Each table is connected through keys.


Part 2 — Question & Answer (Progressive Learning)

Q1. What is a Primary Key?

Answer: A Primary Key is a column (or combination of columns) that uniquely identifies each row in a table.


Q2. Why do we need a Primary Key?

Answer: It ensures that every record can be uniquely identified, avoiding confusion caused by duplicate or changing values like names.


Q3. Can two rows have the same Primary Key?

Answer: No. A Primary Key must always be unique.


Q4. Can a Primary Key contain NULL?

Answer: No. Every row must have a valid Primary Key value.


Q5. Why is using a name as a Primary Key a bad idea?

Answer: Because names can be duplicated, changed, or misspelled. IDs are stable and unique.


Q6. What is a Foreign Key?

Answer: A Foreign Key is a column in one table that references the Primary Key of another table, creating a relationship between the two tables.


Q7. Why do we use Foreign Keys?

Answer: They keep related data connected and prevent invalid references, ensuring data consistency.


Q8. What is referential integrity?

Answer: Referential integrity ensures that every Foreign Key value points to an existing Primary Key, preventing broken relationships between tables.


Q9. What are parent and child tables?

Answer: The table containing the Primary Key is called the parent table. The table containing the Foreign Key is called the child table because it depends on the parent.


Q10. Give a real-life example of Primary and Foreign Keys.

Answer: In an online shopping system, customers.customer_id is the Primary Key. The orders.customer_id column is a Foreign Key that links each order to the customer who placed it.


Part 3 — Top 5 MCQs

1. What is the main purpose of a Primary Key?

A. Store duplicate values

B. Uniquely identify each row

C. Store passwords

D. Sort data

Answer: B


2. Which statement about a Primary Key is correct?

A. It can contain duplicate values.

B. It can contain NULL.

C. It must be unique and cannot be NULL.

D. It is optional for every table.

Answer: C


3. What does a Foreign Key do?

A. Encrypts data

B. References the Primary Key of another table

C. Deletes duplicate rows

D. Sorts the table

Answer: B


4. Which of the following best demonstrates a Foreign Key?

A. students.student_id

B. orders.order_id

C. orders.customer_id referencing customers.customer_id

D. products.price

Answer: C


5. What happens if you try to insert an invalid Foreign Key value (assuming the constraint is enforced)?

A. The database automatically creates the missing parent row.

B. The row is inserted with a warning.

C. The database rejects the insert because the referenced row doesn't exist.

D. The Foreign Key is converted to NULL.

Answer: C


🧠 Chapter 10 Summary

  • A Primary Key (PK) uniquely identifies every row in a table.

  • A Primary Key must be unique and cannot be NULL.

  • A Foreign Key (FK) references a Primary Key in another table.

  • Foreign Keys create relationships between tables and enforce referential integrity.

  • The parent table contains the Primary Key, while the child table contains the Foreign Key.

  • Nearly every real-world relational database—banks, hospitals, e-commerce platforms, schools, and social media—uses Primary and Foreign Keys to keep data connected and consistent.

Memory Trick:
πŸ”‘ Primary Key = "Who am I?" (identity)
πŸ”— Foreign Key = "Who am I related to?" (relationship)

MySQL Chapter 9: Aggregate Functions

Chapter 9: Aggregate Functions

🎯 Goal

By the end of this chapter, you'll understand:

  • What aggregate functions are

  • Why they are used

  • COUNT()

  • SUM()

  • AVG()

  • MIN()

  • MAX()

  • How they work with WHERE

  • How they work with GROUP BY

  • Difference between normal queries and aggregate queries


Part 1 — The Story (Learn Like a Movie)

🎬 The King's Grand School

The king built the biggest school in the kingdom.

There were 100,000 students.

Every student had:

  • Name

  • Age

  • Class

  • Marks

The principal, Mr. Logic, had a magical register.

One day the king asked:

"How many students study in our school?"

Mr. Logic looked at every student...

"One..."

"Two..."

"Three..."

...

After 8 hours...

"100,000."

The king said,

"There has to be a smarter way!"


Enter the Wizard SQL

The wizard smiled.

He waved his wand.

SELECT COUNT(*) FROM students;

Result:

100000

Done in milliseconds.

The king was amazed.


Next Question

The king asked:

"How many total marks have all students scored?"

Mr. Logic started adding.

92

+85

+78

+95

+...

His brain exploded.


Wizard:

SELECT SUM(marks)
FROM students;

8452365

Done instantly.


The Third Question

The king asked:

"What is the average mark?"

Mr. Logic:

"Give me two days."

Wizard:

SELECT AVG(marks)
FROM students;

84.52

Fourth Question

King:

"Who scored the highest marks?"

Mr. Logic:

"I'll check everyone."

Wizard:

SELECT MAX(marks)
FROM students;

100

Fifth Question

King:

"Lowest marks?"

Wizard:

SELECT MIN(marks)
FROM students;

18

The king laughed.

"So instead of checking every student manually, your magic summarizes everything?"

Wizard:

"Exactly."


What Actually Happened?

Aggregate functions don't return individual rows.

They summarize many rows into one answer.

Example

Students

NameMarks
Rahul90
Priya80
John95
Sara85

Normal query

SELECT marks
FROM students;

Output

90
80
95
85

Aggregate query

SELECT AVG(marks)
FROM students;

Output

87.5

Notice:

Many rows → One result.

That's aggregation.


Think of It Like a Calculator

Imagine you have:

10
20
30
40
50

You ask:

"What is the total?"

Calculator returns

150

Database aggregate functions do the same thing.


The Five Most Important Aggregate Functions


1. COUNT()

Counts rows.

Table

Name
Rahul
Priya
John

Query

SELECT COUNT(*)
FROM students;

Output

3

Meaning:

"There are 3 students."


COUNT(column)

Table

NamePhone
Rahul999
PriyaNULL
John888

Query

SELECT COUNT(phone)
FROM students;

Output

2

Why?

Because COUNT(column) ignores NULL.


COUNT(*) vs COUNT(column)

Table

IDPhone
1999
2NULL
3888
COUNT(*)

Returns

3

Because it counts every row.


COUNT(phone)

Returns

2

Because one phone is NULL.


2. SUM()

Adds numbers.

Sales table

Amount
100
250
300

Query

SELECT SUM(amount)
FROM sales;

Output

650

Real-life examples

  • Total revenue

  • Total salary

  • Total expenses

  • Total sales

  • Total orders amount


3. AVG()

Calculates average.

Marks

80
90
70
60

Query

SELECT AVG(marks)
FROM students;

Output

75

Real-life examples

  • Average salary

  • Average rating

  • Average marks

  • Average order value


4. MAX()

Returns biggest value.

Prices

100
200
500
80

Query

SELECT MAX(price)
FROM products;

Output

500

Real-life examples

  • Highest salary

  • Most expensive product

  • Highest marks

  • Latest date


5. MIN()

Returns smallest value.

Prices

100
200
500
80

Query

SELECT MIN(price)
FROM products;

Output

80

Real-life examples

  • Cheapest product

  • Lowest salary

  • Earliest date

  • Youngest age


Aggregate Functions with WHERE

Table

NameMarks
Rahul90
Priya60
John80

Suppose the principal asks:

"What is the average of students scoring at least 80?"

SELECT AVG(marks)
FROM students
WHERE marks >= 80;

Output

85

The WHERE clause filters the rows before the aggregate function is applied.


Aggregate Functions with GROUP BY

Sales

CityAmount
Delhi100
Delhi200
Mumbai300
Mumbai500

Question

"What are total sales in each city?"

SELECT city,
       SUM(amount)
FROM sales
GROUP BY city;

Output

CitySUM
Delhi300
Mumbai800

Without GROUP BY, SUM() would have returned 1100 (one total for the entire table).


Aggregate Functions on Dates

Orders

Date
2024-01-01
2024-03-10
2024-02-15
SELECT MAX(order_date)
FROM orders;

Output

2024-03-10

Latest order.


SELECT MIN(order_date)
FROM orders;

Earliest order.


Can Aggregate Functions Work on Text?

Some can.

Example

COUNT(name)

Works.

But

SUM(name)

❌ Doesn't make sense.

Adding names isn't meaningful.


Common Mistakes

Mistake 1

SELECT SUM(name)

❌ Wrong

Names cannot be added.


Mistake 2

SELECT AVG(city)

❌ Wrong

Cities aren't numbers.


Mistake 3

Expecting multiple rows.

SELECT COUNT(*)
FROM students;

Returns only one row.


Real-Life Examples

Amazon

SELECT SUM(total_price)
FROM orders;

Total revenue.


YouTube

SELECT COUNT(*)
FROM videos;

Total videos.


Netflix

SELECT AVG(rating)
FROM movies;

Average rating.


Hospital

SELECT MAX(age)
FROM patients;

Oldest patient.


School

SELECT MIN(marks)
FROM students;

Lowest score.


Part 2 — Question & Answer (Progressive Learning)

Q1. What is an aggregate function?

Answer: An aggregate function summarizes data from multiple rows into a single result.


Q2. Why are aggregate functions used?

Answer: They help calculate summaries such as totals, averages, minimums, maximums, and counts without manually processing each row.


Q3. What does COUNT() do?

Answer: It counts rows. COUNT(*) counts all rows, while COUNT(column) counts only non-NULL values in that column.


Q4. Why do COUNT(*) and COUNT(column) sometimes return different answers?

Answer: COUNT(*) includes every row. COUNT(column) ignores rows where that column contains NULL.


Q5. What does SUM() do?

Answer: It adds all numeric values in a column and returns the total.


Q6. What does AVG() do?

Answer: It calculates the average of numeric values by adding them together and dividing by the number of non-NULL values.


Q7. What do MIN() and MAX() do?

Answer: MIN() returns the smallest value, while MAX() returns the largest value in a column.


Q8. Can aggregate functions work with WHERE?

Answer: Yes. WHERE filters the rows first, and then the aggregate function operates only on the remaining rows.


Q9. How do aggregate functions work with GROUP BY?

Answer: Instead of producing one summary for the whole table, they produce one summary for each group.


Q10. Give some real-life uses of aggregate functions.

Answer:

  • Banking: Total balance deposited (SUM)

  • E-commerce: Total orders (COUNT)

  • Schools: Average marks (AVG)

  • Hospitals: Oldest patient (MAX)

  • Retail: Cheapest product (MIN)


Part 3 — Top 5 MCQs

1. Which function returns the total number of rows?

A. SUM()

B. AVG()

C. COUNT()

D. MAX()

Answer: C


2. Which function returns the highest value?

A. MIN()

B. AVG()

C. MAX()

D. COUNT()

Answer: C


3. What will this return?

SELECT SUM(price)
FROM products;

A. Highest price

B. Total of all prices

C. Average price

D. Number of products

Answer: B


4. Which statement about COUNT(column) is correct?

A. It counts every row.

B. It ignores NULL values in that column.

C. It only counts duplicate values.

D. It returns the maximum value.

Answer: B


5. Which query returns the average salary of employees earning more than 50,000?

A.

SELECT AVG(salary)
FROM employees
WHERE salary > 50000;

B.

SELECT SUM(salary)
FROM employees;

C.

SELECT COUNT(salary)
FROM employees;

D.

SELECT MAX(salary)
FROM employees;

Answer: A


🧠 Chapter 9 Summary

  • Aggregate functions summarize multiple rows into one result.

  • The five core aggregate functions are:

    • COUNT() → Counts rows or non-NULL values.

    • SUM() → Adds numeric values.

    • AVG() → Calculates the average.

    • MIN() → Finds the smallest value.

    • MAX() → Finds the largest value.

  • WHERE filters rows before aggregation.

  • GROUP BY creates separate summaries for each group instead of one summary for the whole table.

Rule to remember:
Normal SELECT shows individual rows. Aggregate functions show summarized information.

MySQL Chapter 8: Aggregate Functions ⭐⭐

Chapter 8: Aggregate Functions ⭐⭐

🎯 Goal

By the end of this chapter, you'll understand:

  • What aggregate functions are

  • Why they are used

  • The five most important aggregate functions:

    • COUNT()

    • SUM()

    • AVG()

    • MAX()

    • MIN()

  • Difference between row functions and aggregate functions

  • How aggregate functions work with GROUP BY

  • Real-life examples

  • Common beginner mistakes


Part 1 — The Story (Learn Like a Movie)

🎬 The King's Treasure Room πŸ‘‘πŸ’°

In the kingdom of SQL Land, there was a massive treasure vault.

Every treasure chest looked like this:

ChestGold ($)
1$500
2$800
3$300
4$700
5$900

One morning...

The king asked his accountant, Bob,

"How much gold do we have?"

Bob sighed.

He started counting...

$500...

+$800...

+$300...

+$700...

+$900...

Finally...

"$3,200, Your Majesty!"

The king smiled.


Next day...

The king asked,

"How many treasure chests do we own?"

Bob counted again.

1...

2...

3...

4...

5...

"Five chests."


Next day...

"What's the average gold per chest?"

Bob again...

($500+$800+$300+$700+$900)

÷5

= $640


Next day...

"Which chest has the most gold?"

Bob searched every chest.

Maximum

$900


Next day...

"Which chest has the least gold?"

Again...

Minimum

$300


Bob was exhausted.

Every day...

Same work.

Different question.


Then...

A mysterious wizard arrived.

His name was...

πŸ§™ Sir Aggregate

He said,

"Why are you doing everything manually?"

"I have five magical spells."

The king became curious.


Spell 1

COUNT()

The wizard snapped his fingers.

"There are 5 treasure chests."

Done instantly.

Bob's jaw dropped.


Spell 2

SUM()

Another snap.

"Total gold = $3,200."

Done.


Spell 3

AVG()

Another spell.

"Average = $640."

Done.


Spell 4

MAX()

Highest treasure

$900

Done.


Spell 5

MIN()

Smallest treasure

$300

Done.


The king asked,

"How did you answer so quickly?"

The wizard smiled.

"I don't look at each chest individually."

"I treat all the chests as one collection."


Bob looked confused.

Wizard explained.

Imagine...

Five students.

90

85

70

60

95

Instead of asking,

"What is Rahul's mark?"

You ask,

"What is the average mark of the entire class?"

You're asking about the whole group, not one student.

That's exactly what aggregate functions do.


The Festival Continues πŸŽ‰

The king organized a food festival.

Sales

SellerSales ($)
Amit$200
Rahul$300
Amit$400
Rahul$100
Priya$500

The king asked,

"How much did each seller earn?"

Sir Aggregate smiled.

"First, ask Captain GROUP BY to create teams."

Amit Group

$200

$400

Rahul Group

$300

$100

Priya Group

$500

Then Sir Aggregate used

SUM()

Result

SellerTotal Sales
Amit$600
Rahul$400
Priya$500

The king realized...

Captain GROUP BY creates teams.

Sir Aggregate calculates for each team.

They're best friends.


Moral of the Story

Aggregate functions don't work on one row.

They work on many rows together and return one summarized value.


What is an Aggregate Function?

An aggregate function performs a calculation on a collection of rows and returns a single result.

Think of it like asking:

  • Total salary?

  • Average age?

  • Highest marks?

  • Lowest temperature?

  • Number of employees?

These are questions about the whole collection, not individual rows.


Imagine Amazon

Orders

CustomerAmount ($)
Rahul200
Priya500
Rahul300
John100

CEO asks

Total revenue?

Use

SUM()


Number of orders?

COUNT()


Average order value?

AVG()


Highest order?

MAX()


Lowest order?

MIN()


The Five Most Important Aggregate Functions


1. COUNT()

Counts rows.

Students

Name
Rahul
Priya
John

COUNT()

3


Real-life examples

  • Number of users

  • Number of products

  • Number of orders

  • Number of employees


2. SUM()

Adds values together.

Sales

Amount
100
200
300

SUM()

600


Used for

  • Revenue

  • Salary

  • Expenses

  • Profit

  • Total marks


3. AVG()

Calculates average.

Marks

90

80

70

AVG()

80


Used for

  • Average salary

  • Average age

  • Average order value

  • Average rating


4. MAX()

Largest value.

Prices

100

400

250

MAX()

400


Used for

  • Highest salary

  • Highest marks

  • Most expensive product

  • Largest transaction


5. MIN()

Smallest value.

Prices

100

400

250

MIN()

100


Used for

  • Cheapest product

  • Lowest salary

  • Minimum temperature

  • Earliest age


Aggregate Functions vs Normal Functions

Imagine

Students

NameMarks
Rahul90
Priya80
John70

A normal function works on one row at a time.

Example:

Rahul → 90

Priya → 80

John → 70

One input.

One output.


Aggregate function

Looks at

90

80

70

Together.

Returns

Average

80

One result.


Easy way to remember:

Normal Function = Individual

Aggregate Function = Whole Team


Aggregate Functions + GROUP BY

Without GROUP BY

Sales

SellerAmount
Amit100
Amit300
Rahul200

SUM()

600

Whole table.


With GROUP BY

Amit

400

Rahul

200

Now every seller gets their own total.


Real-Life Examples

School

Average marks of each class.

Use

GROUP BY Class

AVG()


Hospital

Patients per doctor.

GROUP BY Doctor

COUNT()


Restaurant

Revenue per waiter.

GROUP BY Waiter

SUM()


Bank

Largest transaction per customer.

GROUP BY Customer

MAX()


Uber

Average trip fare per driver.

GROUP BY Driver

AVG()


Common Beginner Mistakes

❌ Mistake 1

Thinking COUNT(column) always counts every row.

If a column contains NULL, those rows are not counted.

Example:

NamePhone
Rahul99999
PriyaNULL
John88888
  • COUNT(*) = 3 (all rows)

  • COUNT(Phone) = 2 (only non-NULL phone numbers)


❌ Mistake 2

Using SUM() on text columns.

You can only sum numeric values.


❌ Mistake 3

Thinking AVG() rounds automatically.

It can return decimal values.

Example:

80, 81

Average = 80.5


❌ Mistake 4

Expecting MAX() to return an entire row.

It returns only the maximum value from the specified column.


❌ Mistake 5

Forgetting GROUP BY when you want separate summaries for each category.

Without grouping, the aggregate function summarizes the entire table.


Real-World Business Examples

Netflix

  • Average watch time

  • Total subscribers

Amazon

  • Total revenue

  • Largest order

  • Average cart value

Instagram

  • Total likes

  • Average comments

  • Highest viewed reel

Hospital

  • Number of patients

  • Average treatment cost

Bank

  • Total deposits

  • Largest withdrawal

  • Average account balance


Part 2 — Question & Answer (Progressive Learning)

Q1. What is an aggregate function?

Answer: An aggregate function performs a calculation on multiple rows and returns a single summarized result.


Q2. Why do we use aggregate functions?

Answer: To answer summary questions such as total sales, average salary, number of customers, highest marks, or lowest price.


Q3. Which five aggregate functions are used most often?

Answer: COUNT(), SUM(), AVG(), MAX(), and MIN().


Q4. What does COUNT() do?

Answer: It counts rows. COUNT(*) counts all rows, while COUNT(column) counts only non-NULL values in that column.


Q5. What does SUM() do?

Answer: It adds together all numeric values in a column and returns the total.


Q6. What does AVG() do?

Answer: It calculates the average of numeric values in a column.


Q7. What do MAX() and MIN() do?

Answer: MAX() returns the largest value, while MIN() returns the smallest value from a column.


Q8. How do aggregate functions work with GROUP BY?

Answer: GROUP BY divides rows into groups, and aggregate functions calculate a separate summary for each group.


Q9. Give a real-life example of aggregate functions.

Answer: An e-commerce company calculates total revenue using SUM(), counts orders using COUNT(), finds the average order value using AVG(), and identifies the highest and lowest order values using MAX() and MIN().


Q10. What is the difference between a normal function and an aggregate function?

Answer: A normal function processes one row at a time, while an aggregate function processes many rows together and returns one summarized value.


Part 3 — Top 5 MCQs

1. Which aggregate function calculates the total of numeric values?

A. COUNT()

B. SUM()

C. AVG()

D. MAX()

Answer: B


2. Which function returns the highest value?

A. MIN()

B. AVG()

C. MAX()

D. COUNT()

Answer: C


3. Which function calculates the average?

A. SUM()

B. COUNT()

C. AVG()

D. MAX()

Answer: C


4. Which statement about COUNT(*) is correct?

A. It counts only non-NULL values.

B. It counts all rows.

C. It counts only numbers.

D. It returns the largest value.

Answer: B


5. To calculate total sales for each city, which combination is most appropriate?

A. ORDER BY + MAX()

B. WHERE + MIN()

C. GROUP BY + SUM()

D. LIMIT + COUNT()

Answer: C


🧠 Chapter 8 Summary

  • Aggregate functions summarize data across multiple rows.

  • The five essential aggregate functions are:

    • COUNT() → Counts rows or non-NULL values.

    • SUM() → Adds numeric values.

    • AVG() → Calculates the average.

    • MAX() → Finds the largest value.

    • MIN() → Finds the smallest value.

  • Without GROUP BY, an aggregate function summarizes the entire table.

  • With GROUP BY, it produces one summary per group.

  • Aggregate functions are used daily in dashboards, analytics, reports, and business intelligence systems.


πŸŽ“ Mini Memory Trick

Imagine you're a class teacher:

  • πŸ‘¨‍πŸŽ“ COUNT() → "How many students are in my class?"

  • πŸ’° SUM() → "How many total marks did the class score?"

  • πŸ“Š AVG() → "What's the class average?"

  • πŸ† MAX() → "Who scored the highest?"

  • πŸ“‰ MIN() → "What was the lowest score?"

If the principal asks about each class separately, you first use GROUP BY Class, then apply these aggregate functions.


πŸš€ Next Chapter

Chapter 9: Primary & Foreign Keys ⭐

You'll learn one of the most important concepts in relational databases:

  • Why every row needs a unique identity

  • What Primary Keys and Foreign Keys are

  • How tables are connected

  • Why relational databases are called "relational"

  • How databases maintain data integrity and prevent broken relationships.

MySQL Chapter 7: GROUP BY ⭐

Chapter 7: GROUP BY ⭐

🎯 Goal

By the end of this chapter, you'll understand:

  • What GROUP BY is

  • Why we use it

  • How it groups similar data

  • Difference between GROUP BY and ORDER BY

  • How it works with aggregate functions (COUNT, SUM, AVG, MAX, MIN)

  • Real-life examples

  • Common beginner mistakes


Part 1 — The Story (Learn Like a Movie)

🎬 The Grand Ice Cream Festival 🍦

Every year, Data City organized the Grand Ice Cream Festival.

Thousands of people came to buy ice cream.

At the end of the day...

The manager, Mr. SQL, received this sales report.

CustomerFlavor
RahulChocolate
PriyaVanilla
AmanChocolate
JohnStrawberry
SimranChocolate
KaranVanilla
NehaChocolate
ArjunStrawberry

The mayor asked:

"Which flavor is the most popular?"

Mr. SQL looked at the paper...

"Oh no..."

The flavors were scattered everywhere.

Chocolate...

Vanilla...

Chocolate...

Strawberry...

Chocolate...

Vanilla...

Chocolate...

He had to count manually.

Very tiring.


Then...

A magical librarian entered.

His name was...

Captain GROUP BY 🦸

He smiled and said,

"Don't count randomly."

"Let's first gather similar flavors together."

He waved his wand.

The report magically became...

Chocolate Group 🍫

Rahul

Aman

Simran

Neha


Vanilla Group 🍦

Priya

Karan


Strawberry Group πŸ“

John

Arjun


Everyone was surprised.

The mayor asked,

"How many people bought Chocolate?"

Captain GROUP BY replied,

"Easy."

Chocolate Group

4 people

Vanilla Group

2 people

Strawberry Group

2 people

Done.


Next question.

"Which flavor earned the most money?"

Captain GROUP BY said,

"First group by flavor...

then calculate each group's total."

Simple.


Next question.

"What's the average price of each flavor?"

Again...

Group first.

Average later.


Suddenly...

Someone shouted,

"Sort the flavors alphabetically!"

Captain GROUP BY laughed.

"That's not my job."

"My job is grouping."

"My cousin ORDER BY handles sorting."

Everyone laughed.


The mayor asked,

"Can GROUP BY sort?"

Captain GROUP BY replied,

"No."

"I create groups."

"ORDER BY arranges them."


At the end of the festival...

The city realized something.

Whenever they wanted summaries...

They first grouped data.

Only then did they calculate totals, averages, counts, etc.


Moral of the Story

GROUP BY doesn't calculate anything by itself.

It simply says:

"Put similar values into groups."

Then functions like COUNT(), SUM(), or AVG() perform calculations on each group.


Imagine Amazon

Orders

CustomerProduct
RahulLaptop
RahulMouse
PriyaPhone
RahulKeyboard
PriyaCharger

Manager asks:

"How many products did each customer buy?"

Without grouping:

Impossible to answer easily.

With GROUP BY:

Rahul

  • Laptop

  • Mouse

  • Keyboard

3 products

Priya

  • Phone

  • Charger

2 products


What is GROUP BY?

GROUP BY groups rows that have the same value in one or more columns.

Example:

Sales

Product
Laptop
Phone
Laptop
Laptop
Phone

After grouping:

Laptop Group

  • Laptop

  • Laptop

  • Laptop

Phone Group

  • Phone

  • Phone

Now calculations become easy.


Why Do We Use GROUP BY?

Suppose a company has 10 million sales records.

The CEO asks:

"How much money did each city generate?"

Without GROUP BY:

You would manually separate millions of rows.

Impossible.

With GROUP BY:

City A → Total Sales

City B → Total Sales

City C → Total Sales

Done in seconds.


Real-Life Examples

School

Marks

StudentSubjectMarks
RahulMath90
RahulScience85
PriyaMath95

Question:

Average marks of each student.

Group by Student.


Hospital

Appointments

DoctorPatient
Dr. ARahul
Dr. APriya
Dr. BAman

Question:

How many patients did each doctor see?

Group by Doctor.


Bank

Transactions

CustomerAmount
Rahul$500
Rahul$200
Priya$800

Question:

Total money deposited by each customer.

Group by Customer.


Restaurant

Orders

WaiterBill
Amit$50
Amit$30
Ravi$70

Question:

Total sales by each waiter.

Group by Waiter.


GROUP BY + Aggregate Functions

GROUP BY is almost always used with aggregate functions.

Example:

Sales

ProductAmount
Laptop$1000
Laptop$1200
Phone$700
Laptop$900
Phone$800

COUNT()

Question:

How many sales for each product?

Laptop → 3

Phone → 2


SUM()

Question:

Total sales per product?

Laptop

$1000 + $1200 + $900

=

$3100

Phone

$700 + $800

=

$1500


AVG()

Average sale price

Laptop

($1000 + $1200 + $900) / 3

=

$1033.33


MAX()

Highest sale

Laptop

$1200


MIN()

Lowest sale

Laptop

$900


GROUP BY vs ORDER BY

Many beginners confuse these.

GROUP BY

Creates groups.

Example

Before

Chocolate

Vanilla

Chocolate

Chocolate

Vanilla

After grouping

Chocolate Group

Vanilla Group


ORDER BY

Sorts rows.

Example

Before

Chocolate

Vanilla

Apple

After sorting

Apple

Chocolate

Vanilla


Easy way to remember:

  • GROUP BY = Make Teams πŸ‘₯

  • ORDER BY = Make a Queue 🚢🚢🚢


Common Beginner Mistakes

❌ Mistake 1

Thinking GROUP BY sorts data.

It doesn't.

It groups.


❌ Mistake 2

Using GROUP BY without an aggregate function when trying to summarize data.

Grouping alone doesn't calculate totals or averages.


❌ Mistake 3

Thinking GROUP BY removes duplicates.

It doesn't remove rows—it groups them for calculations.


❌ Mistake 4

Expecting GROUP BY to return every individual row.

It returns one result per group when used with aggregate functions.


❌ Mistake 5

Grouping by the wrong column.

Example:

Grouping by Order ID instead of Customer.

Every order becomes its own group.

No useful summary.


Real-World Use Cases

Companies use GROUP BY every day.

Netflix

  • Movies per genre

  • Views per country

Amazon

  • Orders per customer

  • Revenue per product

Instagram

  • Likes per post

  • Followers per country

Uber

  • Trips per driver

  • Earnings per city

Banks

  • Transactions per customer

  • Loans per branch

Hospitals

  • Patients per doctor

  • Appointments per department


Part 2 — Question & Answer (Progressive Learning)

Q1. What is GROUP BY?

Answer: GROUP BY groups rows that have the same value in one or more columns so you can summarize each group.


Q2. Why do we use GROUP BY?

Answer: We use it to create summaries like total sales, average salary, number of students, or highest marks for each category.


Q3. Does GROUP BY calculate totals by itself?

Answer: No. GROUP BY only creates groups. Aggregate functions like SUM() or COUNT() perform the calculations.


Q4. What is an aggregate function?

Answer: An aggregate function performs a calculation on a group of rows, such as counting, summing, averaging, finding the minimum, or finding the maximum.


Q5. What is the difference between GROUP BY and ORDER BY?

Answer: GROUP BY creates groups of similar values, while ORDER BY sorts rows in ascending or descending order.


Q6. Give a real-life example of GROUP BY.

Answer: A school wants to know the average marks of each student. It groups records by student and then calculates the average marks.


Q7. Why is GROUP BY important for businesses?

Answer: Businesses use it to generate reports such as sales by region, orders by customer, revenue by product, or patients by doctor.


Q8. Can GROUP BY work with multiple columns?

Answer: Yes. It can group data based on more than one column, such as grouping by both Department and Job Title.


Q9. What happens if you group by a unique column like Order ID?

Answer: Each order becomes its own group, which usually doesn't produce a useful summary because every group contains only one row.


Q10. Which aggregate functions are most commonly used with GROUP BY?

Answer: COUNT(), SUM(), AVG(), MAX(), and MIN().


Part 3 — Top 5 MCQs

1. What is the main purpose of GROUP BY?

A. Delete rows

B. Sort data

C. Group similar values together

D. Create a table

Answer: C


2. Which function counts the number of rows in each group?

A. SUM()

B. AVG()

C. COUNT()

D. MAX()

Answer: C


3. Which statement is true?

A. GROUP BY automatically sorts data.

B. GROUP BY creates groups for calculations.

C. GROUP BY deletes duplicate rows.

D. GROUP BY changes column names.

Answer: B


4. Which SQL feature is used to sort results?

A. GROUP BY

B. JOIN

C. ORDER BY

D. WHERE

Answer: C


5. A company wants the total sales for each city. Which SQL concept is most appropriate?

A. LIMIT

B. GROUP BY

C. DELETE

D. UPDATE

Answer: B


🧠 Chapter 7 Summary

  • GROUP BY collects rows with the same value into groups.

  • It is mainly used for reporting and summaries.

  • It is commonly paired with aggregate functions:

    • COUNT() → Number of rows

    • SUM() → Total

    • AVG() → Average

    • MAX() → Highest value

    • MIN() → Lowest value

  • GROUP BY groups data, while ORDER BY sorts data.

  • Real-world businesses use GROUP BY constantly to answer questions like:

    • How many orders did each customer place?

    • What is the total revenue per product?

    • Which doctor saw the most patients?

    • Which city generated the highest sales?


πŸš€ Next Chapter

Chapter 8: Aggregate Functions

In the next chapter, we'll dive deeply into the five most important aggregate functions—COUNT(), SUM(), AVG(), MAX(), and MIN()—understanding exactly how they work, when to use them, and the common mistakes developers make with each.

MySQL Chapter 6: Joins ⭐

Chapter 6: Joins ⭐

🎯 Goal

By the end of this chapter, you'll understand:

  • What a JOIN is

  • Why JOINs are needed

  • Why splitting data into multiple tables is a good idea

  • INNER JOIN

  • LEFT JOIN

  • RIGHT JOIN

  • FULL JOIN (concept)

  • CROSS JOIN

  • Self Join (basic idea)

  • Real-life examples

  • Common mistakes beginners make


Part 1 — The Story (Learn Like a Movie)

🎬 The World's Smartest Restaurant

Imagine a huge restaurant called SQL Paradise.

The owner, Mr. Database, wanted everything to be organized.

Instead of writing everything in one giant notebook, he made separate registers.

Register 1 — Customers

Customer IDName
1Rahul
2Priya
3Aman

Register 2 — Orders

Order IDCustomer IDFood
1011Pizza
1022Burger
1031Pasta

One day a waiter asked:

"Who ordered Pizza?"

The chef looked at the Orders register.

Order 101
Customer ID = 1
Pizza

Chef:

"Okay... but who is Customer 1?"

Now he had to open the Customers register.

Customer ID = 1
Rahul

Now he knew:

Rahul ordered Pizza.


The waiter asked another question.

"Show everyone's name with the food they ordered."

Chef sighed.

He had to compare both registers line by line.

Customer Register

Order Register

Customer Register

Order Register

Customer Register

Order Register

It took forever.


Then entered...

Captain JOIN 🦸

Captain JOIN said,

"Why are you searching manually?"

"I'll combine both registers."

Suddenly...

He created a magical report.

NameFood
RahulPizza
PriyaBurger
RahulPasta

Everyone clapped.


The owner asked:

"How did you do that?"

Captain JOIN smiled.

"Both registers have Customer ID."

That common value lets us match the rows.


Imagine Customer ID is like an Aadhaar number.

Even if there are two Rahuls,

Customer IDs remain unique.

So matching becomes easy.


Now the restaurant became very big.

There were new tables.


Customers

IDName
1Rahul
2Priya
3Aman
4John

Orders

OrderCustomer IDFood
1011Pizza
1022Burger
1031Pasta

Notice something?

John never ordered anything.


Now the owner asked,

"Show ALL customers."

Captain JOIN replied,

"I can."

Result:

CustomerFood
RahulPizza
RahulPasta
PriyaBurger
AmanNULL
JohnNULL

Even customers without orders appeared.

That's another kind of JOIN.


Next day...

Someone placed an order.

But due to a bug...

Customer ID = 99

There was no Customer 99.

Order table:

OrderCustomer
10499

Now the owner asked:

"Show ALL orders."

Captain JOIN answered:

OrderCustomer
101Rahul
102Priya
103Rahul
104NULL

The order still appeared.

Even though customer didn't exist.

That's another JOIN.


One day...

The owner said,

"I want EVERY customer matched with EVERY food."

Captain JOIN:

"Seriously?"

Owner:

"Yes."

Result:

Rahul → Pizza

Rahul → Burger

Rahul → Pasta

Priya → Pizza

Priya → Burger

Priya → Pasta

Aman → Pizza

Aman → Burger

...

Everyone got paired with everything.

That's another JOIN.


Finally...

The owner asked,

"Who referred whom?"

Customer table:

IDNameReferred By
1RahulNULL
2Priya1
3Aman2

Now Captain JOIN joined the table...

with...

ITSELF.

CustomerReferred By
PriyaRahul
AmanPriya

Mind blown.


Moral of the Story

JOIN means:

Combining data from two (or more) tables using a common column.

Usually,

that common column is

  • Customer ID

  • User ID

  • Product ID

  • Order ID


Why Do We Split Data?

Imagine storing everything in ONE table.

OrderCustomerPhoneAddressFood
101Rahul9999DelhiPizza
102Rahul9999DelhiBurger
103Rahul9999DelhiPasta

Rahul's information repeats again and again.

Problems:

❌ Wasted space

❌ Hard to update

❌ More errors

Instead:

Customers

Orders

Products

Payments

Different tables.

Much cleaner.

Then JOIN connects them whenever needed.


What is a JOIN?

A JOIN combines rows from two or more tables based on a related column.

Example:

Customers

IDName
1Rahul
2Priya

Orders

OrderCustomer ID
1011
1022

JOIN Result

OrderCustomer
101Rahul
102Priya

Types of JOINs


1. INNER JOIN ⭐⭐⭐

Returns only matching rows.

Customers

IDName
1Rahul
2Priya
3John

Orders

OrderCustomer
1011
1022

Result

CustomerOrder
Rahul101
Priya102

John disappears because he has no order.

Think of it as:

"Show only people who have both customer details and orders."


2. LEFT JOIN ⭐⭐⭐

Returns:

  • Everything from the LEFT table

  • Matching rows from the RIGHT table

Customers

IDName
1Rahul
2Priya
3John

Orders

OrderCustomer
1011
1022

Result

CustomerOrder
Rahul101
Priya102
JohnNULL

John stays because the left table is Customers.


3. RIGHT JOIN

Opposite of LEFT JOIN.

Returns:

  • Everything from the RIGHT table

  • Matching rows from the LEFT table

Useful when you care more about the second table.


4. FULL JOIN (Concept)

Returns:

  • Everything from both tables.

Matches where possible.

Otherwise fills with NULL.

Some databases (like MySQL) don't support FULL JOIN directly.


5. CROSS JOIN

Every row matches every other row.

Customers

Rahul

Priya

Products

Pizza

Burger

Result

Rahul → Pizza

Rahul → Burger

Priya → Pizza

Priya → Burger

This creates all possible combinations.


6. SELF JOIN

A table joins with itself.

Example:

Employees

IDNameManager ID
1CEONULL
2Alice1
3Bob2

Result:

EmployeeManager
AliceCEO
BobAlice

Useful for hierarchies like managers, referrals, or family trees.


Real-Life Examples

Amazon

Tables:

  • Customers

  • Orders

  • Products

  • Payments

  • Addresses

JOINs answer questions like:

  • Which customer bought which product?

  • Which orders are unpaid?

  • Which address belongs to this order?


Hospital

Tables:

  • Patients

  • Doctors

  • Appointments

JOIN:

Patient + Doctor + Appointment


School

Tables:

  • Students

  • Subjects

  • Marks

JOIN:

Student + Subject + Marks


Banking

Tables:

  • Customers

  • Accounts

  • Transactions

JOIN:

Customer + Account + Transaction


Beginner Mistakes

❌ Joining using the wrong columns (e.g., Name instead of ID)

❌ Forgetting the JOIN condition

❌ Expecting unmatched rows in an INNER JOIN

❌ Confusing LEFT JOIN and RIGHT JOIN

❌ Assuming NULL means "0" or an empty string—it means "no matching value."


Part 2 — Question & Answer (Progressive Learning)

Q1. What is a JOIN?

Answer: A JOIN combines related data from two or more tables using a common column.


Q2. Why do we use JOINs?

Answer: Because databases store related information in separate tables to reduce duplication and improve organization. JOINs bring that data together when needed.


Q3. What is usually used to connect two tables?

Answer: A common column, such as Customer ID, User ID, or Product ID.


Q4. Why not store everything in one table?

Answer: It causes repeated data, wastes storage, makes updates difficult, and increases the chance of inconsistencies.


Q5. What does an INNER JOIN return?

Answer: Only the rows where matching values exist in both tables.


Q6. What does a LEFT JOIN return?

Answer: All rows from the left table, plus matching rows from the right table. If no match exists, the right-side columns contain NULL.


Q7. What does a RIGHT JOIN return?

Answer: All rows from the right table, plus matching rows from the left table. If no match exists, the left-side columns contain NULL.


Q8. What is a CROSS JOIN?

Answer: It combines every row from the first table with every row from the second table, producing all possible combinations.


Q9. What is a SELF JOIN?

Answer: A SELF JOIN joins a table with itself, often to represent relationships such as employees and managers or customers and referrals.


Q10. Give some real-life examples where JOINs are used.

Answer: E-commerce (customers + orders), hospitals (patients + doctors), schools (students + marks), banking (customers + transactions), and social media (users + posts).


Part 3 — Top 5 MCQs

1. What is the primary purpose of a JOIN?

A. Delete rows

B. Combine related data from multiple tables

C. Create a database

D. Rename columns

Answer: B


2. Which JOIN returns only matching rows from both tables?

A. LEFT JOIN

B. RIGHT JOIN

C. INNER JOIN

D. CROSS JOIN

Answer: C


3. Which JOIN returns all rows from the left table?

A. INNER JOIN

B. LEFT JOIN

C. RIGHT JOIN

D. CROSS JOIN

Answer: B


4. Which JOIN produces every possible combination of rows?

A. INNER JOIN

B. LEFT JOIN

C. CROSS JOIN

D. SELF JOIN

Answer: C


5. A SELF JOIN is mainly used when:

A. Joining three different tables

B. Joining a table with itself

C. Deleting duplicate rows

D. Creating a new database

Answer: B


🧠 Chapter 6 Summary

  • JOINs combine related data from multiple tables.

  • Tables are split to avoid duplicate information and improve organization.

  • INNER JOIN → only matching rows.

  • LEFT JOIN → all rows from the left table, matching rows from the right.

  • RIGHT JOIN → all rows from the right table, matching rows from the left.

  • FULL JOIN → all rows from both tables (where supported).

  • CROSS JOIN → every row paired with every other row.

  • SELF JOIN → a table joined with itself.

  • In real-world databases, JOINs are among the most frequently used SQL operations because business data is almost always spread across multiple related tables.

➡️ Next Chapter: Chapter 7 — GROUP BY, where you'll learn how databases summarize and group data, such as finding total sales per customer, average salary per department, or number of orders per city.