# @aartii.py on Instagram

- **Type:** Video
- **Original URL:** https://www.instagram.com/p/DSp3kB6Dxn6
- **Gondola URL:** https://gondola.cc/posts/59916597-aartiipy-instagram
- **Thumbnail:** https://img.gondola.cc/tr:w-,h-,fo-auto/postThumbnails/e771eca14a.jpg
- **Posted:** 2025-12-24T17:16:42.000+00:00
- **Account Owner:** Aarti Sinha (@aartii.py) — https://gondola.cc/aartii.py

## Caption

Day 6/7 - SQL Challenge 🎯
TODAY’S QUESTION:
Find departments where the average salary is above the company average.
TABLE:
Employees (id, name, department, salary)
THE SOLUTION:
SELECT 
  department,
 AVG(salary) as avg_salary
FROM Employees
GROUP BY department
HAVING AVG(salary) > (
 SELECT AVG(salary) 
  FROM Employees
);
BREAKDOWN:
AVG(salary) - Calculate average per department
GROUP BY department - Group employees by department
HAVING - Filter AFTER grouping (not WHERE!)
Subquery (SELECT AVG(salary)...) - Company-wide average
EXAMPLE:
Company Average: $80,000

department | avg_salary
-————|————
Engineering | 90,000 ✓ (above company avg)
Sales | 75,000 ✗ (below company avg)
Marketing | 85,000 ✓ (above company avg)
WHY HAVING, NOT WHERE?
— ❌ WRONG (WHERE filters BEFORE grouping)
SELECT department, AVG(salary)
FROM Employees
WHERE AVG(salary) > 80000 ← ERROR!
GROUP BY department;

— ✅ RIGHT (HAVING filters AFTER grouping)
SELECT department, AVG(salary)
FROM Employees
GROUP BY department
HAVING AVG(salary) > 80000;
WHERE vs HAVING:
WHERE: Filters individual rows BEFORE grouping
HAVING: Filters groups AFTER aggregation
COMMON MISTAKES:
❌ Using WHERE instead of HAVING (doesn’t work with aggregates)
❌ Hardcoding company average (not dynamic)
❌ Not understanding subquery execution order
ALTERNATIVE (using WITH):
WITH CompanyAvg AS (
 SELECT AVG(salary) as avg_sal
  FROM Employees
)
SELECT 
  department,
 AVG(salary) as dept_avg
FROM Employees
GROUP BY department
HAVING AVG(salary) > (SELECT avg_sal FROM CompanyAvg);
WHY THIS IS ASKED:
Tests understanding of:
Subqueries in different clauses
GROUP BY + HAVING
Aggregate functions
Query execution order
INTERVIEW TIP:
When comparing aggregates, think HAVING not WHERE.
Day 6/7 complete ✅
One more day! Tomorrow = Query Optimization
#SQLChallenge #Day6 #Subqueries #DataScience #SQL Having ComplexSQL

## Stats

- **Views:** 3,802
- **Likes:** 228
- **Shares:** 0
- **Comments:** 9

## Tags

sqlchallenge, subqueries, sql, day6, datascience

---
Copyright (c) Gondola