đź§  WHY GROUP BY Exists

Let’s start with an example.

Suppose you have this table 👇

emp_id emp_name salary department
1 Abhishek 90000 Engineering
2 Ravi 75000 Engineering
3 Soham 65000 Marketing
4 Amit 90000 Finance
5 Sneha 80000 HR
6 Kiran 70000 Engineering
7 Om 55000 Marketing

Now, if you want to find

“Total salary in each department”

You can’t just run:

SELECT department, SUM(salary) FROM employees;

⚠️ This fails — because the database doesn’t know how to combine multiple rows for each department.

So we tell the DB:

“Hey, group all rows having same department together, and then apply SUM on that group.”

That’s what GROUP BY does.


⚙️ HOW GROUP BY WORKS INTERNALLY

Think of it as a three-phase process inside the database engine:


🔹 Step 1: Filtering (WHERE)