SQL: explain GROUP BY with aggregate functions, and the difference between WHERE and HAVING, with a query example.
ReportedSource: GeeksforGeeks interview experience: Wipro Elite
GROUP BY makes one row per group and aggregates (COUNT/SUM/AVG/MIN/MAX) summarise it. WHERE filters rows before grouping (no aggregates); HAVING filters groups after (can use aggregates).
Constraints
- Table: employees(emp_id, department_id, salary, status). status is 'ACTIVE' or 'INACTIVE'. department_id and salary can be NULL.
- Output columns in order: department_id, employees, avg_salary, top_salary.
- Sort by avg_salary descending, then department_id ascending.
- The reference runs on SQLite; the same query works on PostgreSQL and MySQL.
Sample I/O
in: CREATE TABLE employees (emp_id INTEGER PRIMARY KEY, department_id INTEGER, salary INTEGER, status TEXT); INSERT INTO employees VALUES (1,1,100,'ACTIVE'),(2,1,200,'ACTIVE'),(3,2,50,'ACTIVE'),(4,2,80,'INACTIVE');
out: 1 2 150 200
in: CREATE TABLE employees (emp_id INTEGER PRIMARY KEY, department_id INTEGER, salary INTEGER, status TEXT); INSERT INTO employees VALUES (1,1,10,'ACTIVE'),(2,1,20,'ACTIVE'),(3,2,100,'ACTIVE'),(4,2,300,'ACTIVE'),(5,2,200,'ACTIVE');
out: 2 3 200 300 1 2 15 20
in: CREATE TABLE employees (emp_id INTEGER PRIMARY KEY, department_id INTEGER, salary INTEGER, status TEXT); INSERT INTO employees VALUES (1,1,10,'ACTIVE'),(2,2,20,'ACTIVE'),(3,3,30,'ACTIVE');
out:
Sign up to run your code in the sandbox.
Sign up to run code and get an AI review
You can read and edit the challenge freely — running it in the sandbox and getting AI feedback need a free account.
Sign up freeHints
Reference solution
GROUP BY collapses rows sharing the same values into one row per group; aggregate functions (COUNT, SUM, AVG, MIN, MAX) compute a value per group.
SELECT department_id,
COUNT(*) AS employees,
AVG(salary) AS avg_salary,
MAX(salary) AS top_salary
FROM employees
WHERE status = 'ACTIVE' -- filters rows before grouping
GROUP BY department_id
HAVING COUNT(*) >= 5 -- filters groups after aggregation
ORDER BY avg_salary DESC;
WHERE vs HAVING. WHERE filters individual rows before grouping and cannot use aggregates. HAVING filters groups after aggregation and can. Put conditions on raw columns in WHERE for efficiency.
Rules interviewers test.
- Every selected column must be in
GROUP BYor inside an aggregate (MySQL may allow otherwise, but it is non-standard). COUNT(*)counts rows;COUNT(col)skips NULLs;COUNT(DISTINCT col)counts unique values.- Logical order: FROM -> WHERE -> GROUP BY -> HAVING -> SELECT -> ORDER BY.
See the concept: Join fan-out
| O101 | line 1 | ₹300 |
| O101 | P101 | FAILED |
| O101 | P102 | SUCCESS |
| line 1 | P101 | ₹300 |
| line 1 | P102 | ₹300 |
Wrong: the single ₹300 line is counted once per payment attempt.
Fix: aggregate payments to one row per order first
line 1, paid, ₹300, so SUM = ₹300