MYSQL - WHERE VS GROUP BY VS HAVING

Here is a clear, exam-ready tabular comparison of WHERE, GROUP BY, and HAVING with simple examples 👇


Difference Between WHERE, GROUP BY, and HAVING

FeatureWHEREGROUP BYHAVING
PurposeFilters rowsGroups rows with same valuesFilters groups
Works onIndividual recordsAggregate dataAggregate results
Used with aggregates❌ No✅ Yes✅ Yes
Position in queryBefore GROUP BYAfter WHEREAfter GROUP BY
Can use aggregate functions❌ No (SUM, COUNT)❌ No (only grouping)✅ Yes
Example usesalary > 30000GROUP BY departmentHAVING COUNT(*) > 5

Sample Table: employees

emp_idnamedepartmentsalary
1AIT50000
2BIT60000
3CHR30000
4DHR40000
5ESales20000

1️⃣ WHERE Example (Row-level filtering)

Question: Show employees with salary greater than 40,000.

SELECT * 
FROM employees
WHERE salary > 40000;

✔ Filters individual rows
✔ No aggregation


2️⃣ GROUP BY Example (Grouping rows)

Question: Show total salary per department.

SELECT department, SUM(salary)
FROM employees
GROUP BY department;

✔ Groups rows by department
✔ Uses aggregate function


3️⃣ HAVING Example (Group-level filtering)

Question: Show departments where total salary is more than 80,000.

SELECT department, SUM(salary)
FROM employees
GROUP BY department
HAVING SUM(salary) > 80000;

✔ Filters after grouping
✔ Uses aggregate condition


WHERE vs HAVING (Key Difference)

WHEREHAVING
Filters rowsFilters groups
Cannot use aggregatesCan use aggregates
Executed before GROUP BYExecuted after GROUP BY

Correct Order of Execution (Very Important for Exams)

FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY

💡 Easy Memory Trick

  • WHERE = before grouping

  • HAVING = after grouping

If you want, I can also:

  • Give MCQ-based questions

  • Explain in Hindi

  • Provide real interview questions

Just tell me 👍

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.