Now, let’s move to the next topic of SQL Roadmap:
✅ HAVING Clause
🧠 1. What is HAVING?
HAVING is used to filter grouped data
👉 Think like this:
- WHERE → filters rows (before grouping)
- HAVING → filters groups (after grouping)
⚡ 2. WHERE vs HAVING
Works on
- WHERE: Rows
- HAVING: Groups
Used with
- WHERE: SELECT
- HAVING: GROUP BY
Can use aggregates?
- WHERE: ❌ No
- HAVING: ✅ Yes
💡 3. Basic Syntax
SELECT column, AGG_FUNCTION(column)
FROM table_name
GROUP BY column
HAVING condition;
🎯 4. Examples (Very Important)
👉 Example 1: Departments with more than 2 employees
SELECT department, COUNT() AS total_emp
FROM employees
GROUP BY department
HAVING COUNT() > 2;
👉 Example 2: Departments with average salary > 50k
SELECT department, AVG(salary) AS avg_salary
FROM employees
GROUP BY department
HAVING AVG(salary) > 50000;
⚡ 5. WHERE + HAVING Together
SELECT department, COUNT() AS total_emp
FROM employees
WHERE salary > 30000
GROUP BY department
HAVING COUNT() > 2;
👉 Step-by-step:
1. WHERE → filters employees with salary > 30k
2. GROUP BY → groups by department
3. HAVING → keeps only groups with > 2 employees
🎯 6. Practice Tasks
1. Find departments having more than 3 employees
2. Find departments with average salary > 60k
3. Count employees per department where salary > 40k
4. Show departments with total salary > 1,00,000
5. Find departments with minimum salary > 30k
⚡ Mini Challenge 🔥
👉 Find departments having more than 2 employees AND avg salary > 50k
Double Tap ❤️ For Practice Task Solution
Post #2727
6.79K
- ❤ 19