Here is a clear, exam-ready tabular comparison of WHERE, GROUP BY, and HAVING with simple examples 👇
Difference Between WHERE, GROUP BY, and HAVING
| Feature | WHERE | GROUP BY | HAVING |
|---|---|---|---|
| Purpose | Filters rows | Groups rows with same values | Filters groups |
| Works on | Individual records | Aggregate data | Aggregate results |
| Used with aggregates | ❌ No | ✅ Yes | ✅ Yes |
| Position in query | Before GROUP BY | After WHERE | After GROUP BY |
| Can use aggregate functions | ❌ No (SUM, COUNT) | ❌ No (only grouping) | ✅ Yes |
| Example use | salary > 30000 | GROUP BY department | HAVING COUNT(*) > 5 |
Sample Table: employees
| emp_id | name | department | salary |
|---|---|---|---|
| 1 | A | IT | 50000 |
| 2 | B | IT | 60000 |
| 3 | C | HR | 30000 |
| 4 | D | HR | 40000 |
| 5 | E | Sales | 20000 |
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)
| WHERE | HAVING |
|---|---|
| Filters rows | Filters groups |
| Cannot use aggregates | Can use aggregates |
| Executed before GROUP BY | Executed 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.